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

以上即可实现文件流下载

相关推荐
一颗小青松11 小时前
uniapp输入框fixed定位,导致页面顶起解决方案
前端·uni-app
2501_9151063218 小时前
深入解析无源码iOS加固原理与方案,保护应用安全
android·安全·ios·小程序·uni-app·cocoa·iphone
万能小林子19 小时前
2026 AI开发新范式:Vibe Coding生成网页 + 3分钟打包成App,非技术人也能独立发布自己的App!
人工智能·uni-app·ai编程·web app·vibecoding
白菜__20 小时前
微信小程序网关逆向分析
javascript·微信小程序·小程序·node.js·网络爬虫·微信网关·小程序网关
TANKING-20 小时前
微信小程序订阅消息推送系统(一次性/长期订阅消息推送)
微信小程序·小程序
一颗小青松21 小时前
uniapp 集成友盟并且上传页面路径
前端·vue.js·uni-app
00后程序员张2 天前
HTTPS单向认证、双向认证、抓包原理与反抓包策略详解
网络协议·http·ios·小程序·https·uni-app·iphone
h_65432102 天前
uniapp-APP端获取拍照时的方向角,同一位置横竖屏拍方向角一致
uni-app
梦梦代码精2 天前
LikeShop按摩到家系统:2026年本地生活创业新风口,上门服务O2O源码私有化部署实战
大数据·docker·小程序·uni-app·生活·高并发·开源软件