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

以上即可实现文件流下载

相关推荐
宸翰1 小时前
uni-app 设置 Android 底部虚拟导航栏背景色
android·前端·uni-app
千逐684 小时前
UniApp 鸿蒙实战:音视频与多媒体处理完全指南
华为·uni-app·harmonyos·鸿蒙
handsome09165 小时前
windows开发uniapp如何上架app到app store
uni-app·上架
宠友信息6 小时前
Redis 内容社区源码架构优化与即时通讯数据一致性处理
spring boot·后端·websocket·mysql·uni-app
CHB21 小时前
uni-app x 蒸汽模式 iOS版 性能测试基准报告 Benchmark
ios·uni-app·swiftui
衍生星球21 小时前
SpringBoot3 + Vue3 + 微信小程序如何学习,以及学哪些技术,组件
sql·微信小程序·uni-app·vue·springboot
新华财经频道1 天前
2026微信小程序搭建平台实测测评,优缺点解析
微信小程序·小程序
编程猪猪侠2 天前
UniAppx安卓app实现左侧导航与右侧内容联动滚动
android·uni-app
kidding7232 天前
旋转大转盘小程序
前端·css·微信小程序·小程序·前端框架
千逐682 天前
Uniapp 鸿蒙实战之 AtomGit APP - 仓库详情与文件树浏览
服务器·microsoft·uni-app