vue.js post請求接收後臺的“文件流壓縮包”,觸動瀏覽器進行下載

1. vue  採用 axios 進行post 請求。返回值類型:responseType: 'blob',格式。

import service from 'axios'

const URL_HTTP_DOWN_MORE = "http://10.99.150.50:20001/";

// 創建axios實例
const axios = service.create({
  baseURL:URL_HTTP_DOWN_MORE, // api 的 base_url
 
  timeout: 50000, // 請求超時時間
  contentType: "application/json;charset=utf-8",
  responseType: 'blob',
});
interceptors(axios);

export default axios

2.方法中引入 axios ,方法中請求後臺進行下載。 

import axios from "./index.js"。
return axios({
    url: "你的請求地址",
    method: 'post',
    data: “傳遞參數”,
  }).then(response => { 
    console.log(response);
    let blob = new Blob([response.data], {type: 'application/zip'});
    if('download' in document.createElement('a') ){//// 非IE下載
      let a = document.createElement('a');
      a.style.display = 'none';
      a.href = window.URL.createObjectURL(blob);
      a.download = zipName;
      a.click();
      // URL.revokeObjectURL(a.href) // 釋放URL 對象
      // document.body.removeChild(a);
    }else{ //IE10+
      navigator.msSaveBlob(blob, zipName)
    }

  }).catch(err => {
    console.log(err);
  })

type:類型爲"application/zip",也可以是其他文件類型。 application/pdf  ,application/x-ppt,application/vnd.ms-powerpoint,audio/vnd.rn-realaudio 音頻 ,'application/vnd.ms-excel' 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章