問題: 后端回傳檔案流,前端使用axios下載或者在線預覽
下載檔案流
import axios from 'axios'
// 設定回應型別為blob
axios.get('/api/app/xxx/downloadExcel', { responseType: 'blob' }).then(resp => {
let temp = document.createElement('a') // 創建a標簽
temp.download = 'excel.xls'// 設定下載名稱
// 創建blob物件,在javascript中blob代表一個二進制流物件,不可修改
const blob = new Blob([resp.data], {
// 型別從回應頭中獲取
type: resp.headers["content-type"]
});
// 創建物件url,并賦值給a標簽
let URL = window.URL || window.webkitURL;
temp.href = https://www.cnblogs.com/heirem/archive/2022/12/23/URL.createObjectURL(blob);
// 手動觸發點擊事件
temp.click()
})
提示:document.createElement()方法創建的標簽,不掛載到document樹中,會自動銷毀,不用擔心記憶體問題,
在線預覽pdf
import axios from 'axios'
axios('/api/app/xxx/pdf', { responseType: 'blob' }).then(res => {
const blob = new Blob([res.data], { type: res.headers["content-type"] });
var URL = window.URL || window.webkitURL;
let href = https://www.cnblogs.com/heirem/archive/2022/12/23/URL.createObjectURL(blob);
// 方法一:使用瀏覽器自帶
window.open(href)
// 方法二:使用pdf.js(將pdf.js下載至專案pdf檔案夾)
this.pdfUrl = `/pdf/web/viewer.html?file=${encodeURIComponent(href)}`
})
后端工具類
package com.tons.utils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
public class ResponseFileUtils {
public static void responseFile(HttpServletResponse resp, File file) throws IOException {
responseFile(resp, file, false);
}
public static void responseFile(HttpServletResponse resp, File file, boolean pdfDownload) throws IOException {
// 錯誤處理
if (!file.exists()) throw new RuntimeException(file.getAbsolutePath() + " 檔案不存在");
// 判斷是否pdf
int a = file.getName().toLowerCase().lastIndexOf('.');
int b = file.getName().toLowerCase().indexOf("pdf");
if (a < b && !pdfDownload) {
// 允許瀏覽器預覽
resp.setHeader("content-type", "application/pdf;chartset=UTF-8");
resp.setHeader("Content-Disposition", "fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
} else {
resp.setHeader("content-type", "application/octet-stream");
// attachment 告知瀏覽器,這個檔案流應該是下載的
resp.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
}
// 讀取檔案,回應給瀏覽器
ServletOutputStream out = resp.getOutputStream();
FileInputStream in = new FileInputStream(file);
int size = 0;
byte[] data = https://www.cnblogs.com/heirem/archive/2022/12/23/new byte[1024];
while (true) {
int n = in.read(data, 0, data.length);
if (n <= 0) break;
size += n;
out.write(data, 0, n);
}
resp.setContentLength(size); // 回傳大小
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/540642.html
標籤:其他
上一篇:Vue 3 技術揭秘
