uni-app/vue2:微信小程序实现文件流的下载及预览

有时候后端会返回文件流,而不是完整的文件地址。

实现文件流的下载预览方式如下:

js 复制代码
// 接口地址
const downloadUrl = base_url + "/service/proBasicService/downloadBillFile"
				const token = uni.getStorageSync('token');
				// 参数
				const obj = {}
				uni.request({
					url: downloadUrl, //接口
					method: 'post',
					data: obj,
					responseType: 'arraybuffer',
					header: {
						//请求头
						'X-Access-Token': token
					},
					success: res => {
						console.log('wend', res);
						if (res.statusCode === 200) {
							uni.showLoading({
								title: '下载中...',
								mask: true
							})
							//全局唯一的文件管理器
							const fs = uni.getFileSystemManager();
							// 文件名
							const name = Date.now() + name
							const filePath =`${wx.env.USER_DATA_PATH}/${name}.xlsx`
	
							fs.writeFile({
								//这里填文件的名字
								filePath: filePath,
								data: res.data,
								encoding: "binary",
								success: (res1) => {
									console.log('写入文档成功', res1);
									uni.hideLoading()
									uni.showToast({
										title: '文档下载成功',
										icon: 'none'
									})
									uni.openDocument({
										showMenu: true,
										filePath: filePath,
										success: function(res2) {
											console.log('打开文档成功');
										},
										fail: err => {
											console.log('fail 1', err);
										}
									});
								},
								fail: err => {
									uni.hideLoading()
									uni.showToast({
										title: '文档下载失败',
										icon: 'none'
									})
									console.log('fail', err);
								}
							})
						}
					},
					fail: err => {
						uni.hideLoading()
						uni.showToast({
							title: '文档下载失败',
							icon: 'none'
						})
					}
				})

有时会出现本地存储文件超过10M的问题,可以尝试清除缓存,如下:

js 复制代码
onLoad() {
			uni.getSavedFileList({
				success: function(res) {
					if (res.fileList.length > 0) {
						// 删除本地存储的文件
						uni.removeSavedFile({
							filePath: res.fileList[0].filePath
						});
					}
				}
			});
		},

以上即可实现文件流下载

相关推荐
2501_9159184116 小时前
详解iOS App上架至App Store的全流程步骤与注意事项
android·macos·ios·小程序·uni-app·cocoa·iphone
anyup17 小时前
终于在今天入选了 Gitee GVP,这真值得庆祝~
前端·uni-app·开源
虚惊一场1 天前
撤销为什么只需要 pop:用事件重放实现离线台球计分
微信小程序·uni-app
虚惊一场1 天前
从一个小程序到一座工具箱:uni-app 分包与 Flask 微服务实践
微信小程序·uni-app
beichenxingzhui1 天前
茶饮品牌“新品口感盲测问答”:适合微信小程序与互动页的工具 Top 3
微信小程序·小程序
Cry丶1 天前
【已解决】adb devices 能识别手机,但 HBuilderX 搜索不到设备的避坑指南
android·adb·uni-app·hbuilderx·真机调试
清风programmer2 天前
H5与小程序通信
前端·vue.js·uni-app
海纳百川·纳海川2 天前
数字化升级,让废品回收更简单高效
大数据·微信小程序·小程序
VX_bysjlw9853 天前
基于微信小程序的宠物用品商城系统-后端74346-计算机毕设原创(免费领源码+带部署教程)
java·redis·微信小程序·eclipse·mybatis·idea·微信开发者工具
一只昀3 天前
基于微信小程序的咖啡店点餐小程序
微信小程序·小程序