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
						});
					}
				}
			});
		},

以上即可实现文件流下载

相关推荐
胡西风_foxww2 小时前
微信小程序转Vue2组件智能提示词
微信小程序·小程序·提示词·智能体·vue2组件
2501_916007475 小时前
iPhone查看App日志和系统崩溃日志的完整实用指南
android·ios·小程序·https·uni-app·iphone·webview
2501_915918417 小时前
iOS 抓不到包怎么办?全流程排查思路与替代引导
android·ios·小程序·https·uni-app·iphone·webview
HebyH_8 小时前
uniapp如何封装uni.request 全局使用
uni-app
换日线°18 小时前
css 不错的按钮动画
前端·css·微信小程序
qq_4275060820 小时前
JavaScript和小程序写水印的方法示例
前端·算法·微信小程序
冥王 • 雷利1 天前
Notepad++插件安装
notepad++
随笔记1 天前
uniapp蓝牙连接设备并发送接收信息
javascript·uni-app·app
脑袋大大的1 天前
从“PPT动画”到“丝滑如德芙”——uni-app x 动画性能的“终极奥义”
前端·javascript·nginx·uni-app·uniapp·app开发·混合开发
随笔记1 天前
uniapp开发的app原生操作手机系统文件
前端·javascript·uni-app