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)
相关推荐
KaMeidebaby37 分钟前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl2 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl2 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
nuIl2 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl2 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf2 小时前
Python 异常处理
前端·后端·python
sugar__salt2 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
独特的螺狮粉2 小时前
篮球集训班器具管理系统 - 鸿蒙PC Electron框架完整技术实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙
pusheng20252 小时前
IFSJ全英文专访:中国创新力量重塑先进气体感知技术,赋能全球关键基础设施安全
前端·网络·人工智能·物联网·安全
AI_零食3 小时前
番茄钟鸿蒙PC Electron框架完成:状态机、定时器管理与专注力工具设计
前端·javascript·华为·electron·开源·鸿蒙·鸿蒙系统