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)
相关推荐
不简说19 分钟前
JS 代码技巧 vol.5 — 10 个错误处理套路,从 try/catch 到 Error Boundary
前端·javascript·程序员
wordpress资料库22 分钟前
Next.js更适合移动开发 不适合web开发
开发语言·前端·javascript·next.js
卷无止境32 分钟前
Quarkdown:赋予 Markdown 超能力的现代排版系统
前端·markdown
BerryS3N1 小时前
C++23新特性在CLion中的实战体验:从语法糖到生产力提升
前端·c++23
申君健24864182772022 小时前
# WebGPU 的渲染原理与 Shader
前端
随风123weber2 小时前
从前端响应式到后端背压:深度拆解生成式 UI(Generative UI)
前端
用户059540174462 小时前
用 Pytest 接管大模型记忆存储测试,状态一致性问题减少 90%
前端·css
IT_陈寒2 小时前
JavaScript的异步地狱里,我的Promise掉进了微任务陷阱
前端·人工智能·后端
嘟嘟07172 小时前
大前端工程师必学:用 BFF 架构搭建安全的 AI 流式应用
前端
meilindehuzi_a2 小时前
Vue 项目中的前端 BFF:跨域代理与流式请求实战
前端·javascript·vue.js