vue實現下載檔案流完整前後端程式碼
阿新 • • 發佈:2020-11-18
使用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); 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' }); };
這樣即可成功下載。
關於vue.js的學習教程,請大家點選專題vue.js元件學習教程、Vue.js前端元件學習教程進行學習。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。