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)
相关推荐
妖孽白小白37 分钟前
el-select的内容续写实现
前端·vue.js·elementui
不可能片场1 小时前
Electron 主进程热补丁:单行 JS 安全打法
前端·electron
梨想橙汁1 小时前
Pinia 状态管理实战:定义 Store、修改数据、模块拆分
前端·vue.js
高申航1 小时前
Vue 3 + DYMO Connect Framework 实战:从标签模板到打印服务的完整实现
前端·javascript·vue.js
梨想橙汁1 小时前
Vue3 组件开发:生命周期钩子,组件之间通信全方案
前端·vue.js
雪芽蓝域zzs1 小时前
分页组件 + el-config-provider 中文国际化 + 靠右布局
前端·javascript·vue.js
恋猫de小郭1 小时前
iPhone Duo 适配详解,需要改变的不止是布局模型
前端·flutter·ios
萧行之1 小时前
Observable Plot 源码深度解析——4 核心抽象逐项学习
前端·学习·数据可视化
今日无bug2 小时前
为什么大模型回答总是一个字一个字蹦出来?聊聊 SSE 流式输出与 BFF 层的那些事
前端·llm
CIO_Alliance2 小时前
AI微调系列(1)| 全量微调、LoRA、QLoRA 三种方案怎么选
前端·人工智能·神经网络·机器学习·embedding·企业ai转型