您现在的位置是:网站首页> 编程资料编程资料
vue如何使用文件流进行下载(new Blob)_vue.js_
2023-05-24
298人已围观
简介 vue如何使用文件流进行下载(new Blob)_vue.js_
vue使用文件流进行下载(new Blob)
封装方法
function getExel(url, params, index) {+ return new Promise(function(resolve, reject) { let data = { method: "GET", url:url, headers: { 'token': gettoken("token") }, responseType: 'arraybuffer' } resolve(axios(data)); }) }注意:responseType应设置为:'arraybuffer'
发送请求($Api已经挂载在了vue对象上,所以可以这么使用)
this.$Api.getExel("/goodsCheckService/v1/planMaterial/export?idList="+idArray) .then(response => { let a = document.createElement('a'); //ArrayBuffer 转为 Blob let blob = new Blob([response.data], {type: "application/vnd.ms-excel"}); let objectUrl = URL.createObjectURL(blob); a.setAttribute("href",objectUrl); a.setAttribute("download", '计划单电子表格.xls'); a.click(); });vue下载文件流完整前后端代码
使用Vue时,我们前端如何处理后端返回的文件流
首先后端返回流,这里我把流的动作拿出来了,我很多地方要用
/** * 下载单个文件 * * @param docId */ @GetMapping("/download/{docId}") public void download(@PathVariable("docId") String docId, HttpServletResponse response) { outWrite(response, docId); } /** * 输出文件流 * @param response * @param docId */ private void outWrite(HttpServletResponse response, String docId) { ServletOutputStream out = null; try { out = response.getOutputStream(); // 禁止图像缓存。 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); byte[] bytes = docService.downloadFileSingle(docId); if (bytes != null) { MagicMatch match = Magic.getMagicMatch(bytes); String mimeType = match.getMimeType(); response.setContentType(mimeType); response.addHeader("Content-Length", String.valueOf(bytes.length)); out.write(bytes); } out.flush(); } catch (Exception e) { UnitedLogger.error(e); } finally { IOUtils.closeQuietly(out); } }前端这里我引入了一个组件 js-file-download
npm install js-file-download --save
然后在Vue文件中添加进来
import fileDownload from "js-file-download"; // 文档操作列对应事件 async handleCommand(item, data) { switch (item.key) { case "download": var res = await this.download(data); return fileDownload(res, data.name); ... default: } // 刷新当前层级的列表 const folder = this.getLastFolderPath(); this.listClick(folder.folderId, folder.name); }, // 下载 async download(row) { if (this.isFolder(row.type)) { return FolderAPI.download(row.id); } else { return DocAPI.download(row.id); } },docAPI js 注意需要设置responseType
/** * 下载单个文件 * @param {*} id */ const download = (id) => { return request({ url: _DataAPI.download + id, method: "GET", responseType: 'blob' }); };这样即可成功下载
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- 前端算法题解leetcode114二叉树展开为链表_javascript技巧_
- Vue transition组件简单实现数字滚动_vue.js_
- vue给数组中对象排序 sort函数的用法_vue.js_
- .env在mode文件中如何添加注释详解_vue.js_
- 微信小程序如何在页面跳转时进行页面导航_javascript技巧_
- Vue项目中使用iView组件库设置样式不生效的解决方案_vue.js_
- JS前端使用Canvas快速实现手势解锁特效_JavaScript_
- vue3中路由传参query、params及动态路由传参详解_vue.js_
- 如何只用echarts做个仿3d地图功能_javascript技巧_
- Vue2 中自定义图片懒加载指令 v-lazy实例详解_vue.js_
