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)
相关推荐
问心无愧05134 小时前
ctf show web入门160 161
前端·笔记
李小白664 小时前
第四天-WEB服务器基本原理,IIS服务
运维·服务器·前端
humcomm4 小时前
AI编程时代新前端职位
前端·ai编程
好家伙VCC5 小时前
Web Components主题热切换方案揭秘
java·前端
甲维斯5 小时前
Kimi版超级玛丽效果“惊人”,配额不足5厘米!
前端·人工智能
hboot5 小时前
AI工程师第一课 - Python
前端·后端·python
凉菜凉凉5 小时前
AI时代,被抛弃的前端
前端·ai
console.log('npc')6 小时前
AI前端工程与生成式UI学习路线
前端·人工智能·ui
梦曦i6 小时前
uni-router v1.1.1发布:守卫超时保护+路由监听
前端·uni-app
qq_2518364576 小时前
基于java Web网络订餐系统设计与实现 源码文档
java·开发语言·前端