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)
相关推荐
前端小端长36 分钟前
qiankun 微前端应用入门教程:从搭建到部署
前端
yinuo3 小时前
前端跨页面通讯终极指南⑥:SharedWorker 用法全解析
前端
PineappleCoder7 小时前
还在重复下载资源?HTTP 缓存让二次访问 “零请求”,用户体验翻倍
前端·性能优化
拉不动的猪7 小时前
webpack编译中为什么不建议load替换ast中节点删除consolg.log
前端·javascript·webpack
李姆斯7 小时前
Agent时代下,ToB前端的UI和交互会往哪走?
前端·agent·交互设计
源码获取_wx:Fegn08958 小时前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
闲谈共视8 小时前
基于去中心化社交与AI智能服务的Web钱包商业开发的可行性
前端·人工智能·去中心化·区块链
CreasyChan8 小时前
C# 反射详解
开发语言·前端·windows·unity·c#·游戏开发
JIngJaneIL9 小时前
基于Java+ vue智慧医药系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
hashiqimiya10 小时前
两个步骤,打包war,tomcat使用war包
java·服务器·前端