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

以上即可实现文件流下载

相关推荐
快起来搬砖了几秒前
实现一个优雅的城市选择器组件 - Uniapp实战
开发语言·javascript·uni-app
数学分析分析什么?4 分钟前
Uniapp中使用renderjs实现OpenLayers+天地图的展示与操作
uni-app·openlayers·天地图·renderjs
海绵宝宝不喜欢侬6 分钟前
UniApp微信小程序-实现蓝牙功能
微信小程序·uni-app
Python大数据分析3 小时前
uniapp微信小程序商品列表数据分页+本地缓存+下拉刷新+图片懒加载
缓存·微信小程序·uni-app
机构师3 小时前
<uniapp><指针组件>基于uniapp,编写一个自定义箭头指针组件
javascript·uni-app·vue·html
小白_ysf3 小时前
uniapp和vue3项目中引入echarts 、lime-echart(微信小程序、H5等)
微信小程序·uni-app·echarts·h5·lime-echart
imHere·3 小时前
UniApp 分包异步化配置及组件引用解决方案
微信小程序·uni-app·分包
2501_916013745 小时前
App 上架全流程指南,iOS App 上架步骤、App Store 应用发布流程、uni-app 打包上传与审核要点详解
android·ios·小程序·https·uni-app·iphone·webview
canglingyue5 小时前
微信小程序加速计开发指南
微信小程序·小程序
0x0005 小时前
Uniapp - 自定义 Tabbar 实现
前端·uni-app