vue實現(xiàn)下載文件流完整前后端代碼
更新時間:2020年11月17日 14:56:51 作者:小狐貍和小兔子
這篇文章主要為大家詳細介紹了vue實現(xiàn)下載文件流完整前后端代碼,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
使用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前端組件學習教程進行學習。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue打包上傳服務器加載提示錯誤Loading chunk {n} failed
這篇文章主要為大家介紹了vue打包上傳服務器加載提示錯誤Loading chunk {n} failed解決方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
Vue.js中使用iView日期選擇器并設置開始時間結束時間校驗功能
本文通過實例代碼給大家介紹了Vue.js中使用iView日期選擇器并設置開始時間結束時間校驗功能,需要的朋友可以參考下2018-08-08
解決vant title-active-color與title-inactive-color不生效問題
這篇文章主要介紹了解決vant title-active-color與title-inactive-color不生效問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
詳解vue 中使用 AJAX獲取數(shù)據(jù)的方法
本篇文章主要介紹了詳解vue 中使用 AJAX獲取數(shù)據(jù)的方法,在VUE開發(fā)時,數(shù)據(jù)可以使用jquery和vue-resource來獲取數(shù)據(jù),有興趣的可以了解一下。2017-01-01

