1. 程式人生 > 其它 >vue+spingboot 實現伺服器端檔案下載功能

vue+spingboot 實現伺服器端檔案下載功能

      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; },