vue3 和springboot配合如何實現服務器端文件的下載。
先看springboot的后台代碼:
@PostMapping("/download") @ResponseBody public void downloadWord(HttpServletResponse response, HttpServletRequest request,@Valid String filePath) { try { //獲取文件的路徑filePath是服務器端存放文件的完整地址 File file = ResourceUtils.getFile(filePath); //文件后綴名 String suffex = filePath.split("\\.")[1]; // 讀到流中 InputStream inStream = new FileInputStream(file);//文件的存放路徑 // 設置輸出的格式 response.reset(); response.setContentType("bin");
//文件名中午亂碼的問題沒有解決所以,文件名后端都叫1.XXX,最后文件名由前端重新修改 response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("1."+suffex, "UTF-8")); // 循環取出流中的數據 byte[] b = new byte[200]; int len; while ((len = inStream.read(b)) > 0) { response.getOutputStream().write(b, 0, len); } inStream.close(); } catch (IOException e) { e.printStackTrace(); } }
vue端:
網絡請求使用axios ,文件下載使用file-saver
npm install file-saver --save
bower install file-saver
注:axios參照vue axiox網絡請求 ,如下代碼不在同一個文件內,根據需求自行規划
import axios from "axios"; // 引用axios import qs from 'qs'; const instance = axios.create({ baseURL: config.baseUrl.dev, timeout: 60000, responseType: 'blob', //這里是關鍵 withCredentials: true, crossDomain: true, transformRequest: [function(data) { data = qs.stringify(data); return data; }], headers: { 'apiVersion': 'v1', } }); export function postBlob(url, data = {}) { return new Promise((resolve, reject) => { instance.post(url, data) .then((response) => { resolve(response); }) .catch((err) => { reject(err); }); }); } //資源下載的接口定義 export const resourceDownload = (params) => postBlob("/zy/download", params); //資源下載的方法 downLoadfunction(index) { //獲得資源的名稱 let fileName = this.getFileName(this.data1[index].resourcesPath); //指定資源在服務期端的路徑 let paramter = { filePath: this.data1[index].resourcesPath }; resourceDownload(paramter).then(res => { var FileSaver = require('file-saver'); var blob = new Blob([res.data], { type: "text/plain;charset=utf-8" }); FileSaver.saveAs(blob, fileName) }) .catch(error => {}); }, //獲取文件名 getFileName(url) { let name = ""; if (url !== null && url !== "") { name = url.substring(url.lastIndexOf("/") + 1); } else { name = "無"; } return name; },