uniapp小程序接口返回文件流下载文件

uniapp小程序接口返回文件流数据,下载导出文件

使用uni.request post方法获取文件流,如果是get可以使用uni.downloadFile

复制代码
exportfun(){
	uni.request({
		url: 'xxx',
		data: {},
		method:'POST',
		responseType: 'arraybuffer',
		header: {},
		success: (res) => {
			const fs = uni.getFileSystemManager(); // 获取全局唯一的文件管理器 
			const fileName = !res.header['Content-Disposition']?'xxx文件':decodeURIComponent(res.header['Content-Disposition'].match(/filename="?(.+)"?/)[1]) //文件名
			fs.writeFile({ //写文件
				// uni.env.USER_DATA_PATH 是小程序提供的访问用户文件路径的变量
				filePath: uni.env.USER_DATA_PATH + '/' + fileName,
				data: res.data,  // res.data就是接口返回的文件流
				encoding: "binary", //二进制流文件必须是 binary
				success(e) {
					uni.openDocument({ // 打开文档
						filePath: uni.env.USER_DATA_PATH + '/' + fileName, // 上面存入的文件路径
						showMenu: true, // 显示右上角菜单
						success: function(res2) {
							console.log("打开文件",res2); 
						},
					})
				}
			})
		}
	});
}

获取 返回的文件流 文件名称

复制代码
const Disposition=res.header['Content-Disposition']
const fileName =Disposition.match(/filename="?(.+)"?/)[1]
//如果返回乱码需要使用decodeURIComponent转换
fileName =decodeURIComponent(fileName)
相关推荐
爱勇宝6 小时前
大多数人不是在使用 AI 赚钱,而是在帮 AI 公司赚钱
前端·后端·程序员
冬奇Lab7 小时前
每日一个开源项目(第143篇):page-agent - 纯 JS 的网页 GUI Agent,无需截图、无需插件、无需后端
前端·人工智能·agent
IT_陈寒11 小时前
React的这个渲染问题连官方文档都没说清楚
前端·人工智能·后端
追逐时光者13 小时前
别再满网找零散工具了,腾讯 QQ 浏览器这个“帮小忙”工具箱真能省时间
前端·后端
Asmewill15 小时前
grep&curl命令学习笔记
前端
spmcor15 小时前
身份证读卡“无感登录”方案实践:从手动点击到自动检测
uni-app
stringwu15 小时前
Flutter 开发必备:MVI 架构的高效实现指南
前端·flutter
用户21366100357216 小时前
Vue2组件化开发与父子通信
前端·vue.js
Momo__16 小时前
TypeScript satisfies 操作符——比 as 更安全的类型守门员
前端·typescript
用户21366100357216 小时前
Vue2事件系统与指令进阶
前端·vue.js