天天看點

vue檔案流下載下傳檔案

背景傳回檔案流格式,前端進行下載下傳對應檔案
//接口
export function fileDataDownloadIO(params) {
  return request({
    url: '/fileData/downloadIO',
    method: 'get',
    params,
    responseType: 'blob', //設定響應格式
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded', //設定請求頭,根據背景需要格式
    }
  })
}
           
//下載下傳按鈕
<el-button type="primary" class="addBtn" @click="addItem">下載下傳所選</el-button >
           
背景傳回檔案流
vue檔案流下載下傳檔案
通過blob轉換擷取需要的data和改變檔案名
vue檔案流下載下傳檔案
//調用方法
 addItem() {
          let res = await fileDataDownloadIO({ id: downloadSelection });
          const blob = new Blob([res.data], { type: res.data.type });
          console.log("下載下傳檔案的值,", res);
          const fileName = res.headers["content-disposition"].split(";");
          const filename2 = fileName[1].split("=");
          const filename3 = decodeURIComponent(filename2[1]);
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob);
          downloadElement.href = href;
          downloadElement.download = filename3;
          console.log("filename3", filename3);
          document.body.appendChild(downloadElement);
          downloadElement.click();
          document.body.removeChild(downloadElement); //移除元素;防止連續點選建立多個a标簽
          window.URL.revokeObjectURL(href);
    },
           
下載下傳成功顯示
vue檔案流下載下傳檔案

遇到問題

1.如果出現類似問題

This XML file does not appear to have any style information associated with it. The document tree is shown below.
           

原因:背景傳回type格式有誤

解決方法:叫背景改

2.下載下傳的檔案是這樣的

vue檔案流下載下傳檔案

原因:因為沒設定檔案名

解決方法:加上檔案名就行,在傳回的header裡面,如果沒有的話叫背景給

借鑒于:https://blog.csdn.net/qq_45018844/article/details/125558770

繼續閱讀