接口返回zip压缩包流下载

zip

       if (response.data.type == "application/zip") {
            let contentPosition = response.headers["content-disposition"];
            contentPosition = contentPosition.split(";")[1];
            let fileName = contentPosition.split("=")[1];
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              const blob = new Blob([response.data], {
                type: "application/zip",
              });
              window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
              const blob = new Blob([response.data], {
                type: "application/zip",
              });
              const url = window.URL.createObjectURL(blob);
              const link = document.createElement("a");

              link.href = url;
              link.download = decodeURI(fileName);
              link.click();
              URL.revokeObjectURL(url);
            }
          }

pic/其他文件

     if (response.data.type == "application/octet-stream") {
            let contentPosition = response.headers["content-disposition"];
            contentPosition = contentPosition.split(";")[1];
            let fileName = contentPosition.split("=")[1];
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
              const blob = new Blob([response.data], {
                type: "application/octet-stream",
              });
              window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
              const blob = new Blob([response.data], {
                type: "application/octet-stream",
              });
              const url = window.URL.createObjectURL(blob);
              const link = document.createElement("a");

              link.href = url;
              link.download = decodeURI(fileName);
              link.click();
              URL.revokeObjectURL(url);
            }
          }

//httpRequest

/*
 * @Autor: Wwh
 * @Date: 2021-11-24 22:34:15
 * @LastEditors: Do not edit
 * @LastEditTime: 2022-08-15 14:45:30
 * @Description: In User Settings Edit
 * @FilePath: \neiwang-project-V1.0.0\src\https\httpRequest.js
 */
import axios from 'axios'
import Qs from 'qs'
import { baseUrl } from './env'

// 超时时长
axios.defaults.timeout = 600000
//填写域名
axios.defaults.baseURL = baseUrl

// 添加请求拦截器
axios.interceptors.request.use(
  function (config) {
    /* if (window.baseConfig.addToken) {
      let token = sessionStorage.getItem('token')
      if (!token) {
      } else {
        config.headers = {
          Authorization: token,
        }
      }
    } */
    // 在发送请求之前做些什么
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)
// 响应拦截器即异常处理
axios.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    return response
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

export { axios }

export default class RequestMethod {
  /**
   * 封装fetch方法
   * @param url
   * @param data
   * @returns {Promise}
   */
  static fetch(url, params) {
    return new Promise((resolve, reject) => {
      axios
        .get(url, {
          params: params,
        })
        .then((response) => {
          resolve(response.data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  // static download(params,url){
  //    return axios
  //    .get(
  //        baseUrl+url,//接口地址
  //        params,
  //        // responseType: `arraybuffer` //一定要写
  //        {responseType:'blob'},//将文件流转成blob对象
  //        {noErrorMsg:true}
  //    )

  // }
  // static downloadDefaultExcelTemplate(urls) {
  //    let token = sessionStorage.getItem("token")
  //    const url = baseUrl + urls
  //    const a = document.createElement('a')
  //    // 使用fetch方法获取response.headers响应头
  //    fetch(url,{ headers: { "Authorization": token } }).then(res => {
  //      console.log('res', res)
  //      // 切割出文件名
  //      const fileNameEncode = res.headers.get('content-disposition').split('filename=')[1]
  //      // 解码
  //      const fileName = decodeURIComponent(fileNameEncode)
  //      console.log('fileName', fileName)
  //      // 使用blob()方法获取blob对象数据
  //      res.blob().then(
  //        res => {
  //          console.log('bolbs', res)
  //          // 设置type类型
  //          const blob = new Blob([res], {
  //            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; application/octet-stream'
  //          })
  //          const fileUrl = window.URL.createObjectURL(blob)
  //          a.href = fileUrl
  //          console.log('url', fileUrl)

  //          a.setAttribute('download', fileName)
  //          a.style.display = 'none'
  //          a.click()
  //          a.remove()
  //        }
  //      )
  //    })
  //   }

  static download(url, params = {}, type = 'baseUrl') {
    Analysis.setBaseUrl(type)
    return new Promise((resolve, reject) => {
      axios
        .get(url, { params }, { responseType: 'blob' }, { noErrorMsg: true })
        .then((response) => {
          resolve(response.data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  /**
   * 封装get方法
   * @param url
   * @param data
   * @returns {Promise}
   */
  static get(url, params = {}, type = 'baseUrl') {
    Analysis.setBaseUrl(type)
    return new Promise((resolve, reject) => {
      axios
        .get(url, { params })
        .then((response) => {
          resolve(response.data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
  /**
   * 封装post请求
   * @param url  服务地址
   * @param data  请求参数
   * @param types  请求地址  默认 baseUrl
   * @param request_Method  请求方法  默认 application/x-www-form-urlencoded
   *
   * @returns {Promise}
   */

  static post(
    url,
    data = {},
    types = 'baseUrl',
    request_Method = 'application/x-www-form-urlencoded'
  ) {
    Analysis.setBaseUrl(types)
    if (request_Method == 'application/x-www-form-urlencoded') {
      return new Promise((resolve, reject) => {
        axios
          .post(url, Qs.stringify(data), {
            headers: {
              'Content-Type':
                'application/x-www-form-urlencoded;multipart/form-data;',
            },
          })
          .then((response) => {
            // console.log(response)
            if (response != undefined && response.data != undefined) {
              resolve(response.data)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    } else if (request_Method == 'application/json') {
      return new Promise((resolve, reject) => {
        axios
          .post(url, data, { headers: { 'Content-Type': 'application/json' } })
          .then((response) => {
            // console.log(response)
            if (response != undefined && response.data != undefined) {
              resolve(response.data)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    } else {
      return new Promise((resolve, reject) => {
        axios
          .post(url, Qs.stringify(data))
          .then((response) => {
            // console.log(response)
            if (response != undefined && response.data != undefined) {
              resolve(response.data)
            }
          })
          .catch((err) => {
            reject(err)
          })
      })
    }
  }
  /**
   * 封装post请求头
   * @param url  服务地址
   * @param data  请求参数
   * @param types  请求地址  默认 baseUrl
   * @param request_Method  请求方法  默认 application/x-www-form-urlencoded
   *
   * @returns {Promise}
   */
  static postHead(url, data, types = 'baseUrl', headers) {
    Analysis.setBaseUrl(types)
    return new Promise((resolve, reject) => {
      axios
        .post(url, data, { headers: headers })
        .then((response) => {
          // console.log(response)
          if (response != undefined && response.data != undefined) {
            resolve(response.data)
          }
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  /**
   * 封装delete请求 参数当做java对象来封装接收
   * @param url
   * @param data
   * @returns {Promise}
   */

  static deleteMethod(url, data = {}, types = 'baseUrl') {
    Analysis.setBaseUrl(types)
    return new Promise((resolve, reject) => {
      axios.delete(url, { data: data }).then(
        (response) => {
          resolve(response.data)
        },
        (err) => {
          reject(err)
        }
      )
    })
  }
}

class Analysis {
  static setBaseUrl(type) {
    // console.log(type)
    switch (type) {
      case 'baseUrl':
        axios.defaults.baseURL = baseUrl
        break

      default:
        axios.defaults.baseURL = baseUrl
        break
    }
  }
}

请求+一个参数=> responseType: 'blob',

  axios({
        method: 'get',
        url: homeApi.getProduct,
        params: {
          id: this.changeIds(ids),
          prodName: name||'',
          time: newTimes,
        },
        responseType: 'blob',
      })

你可能感兴趣的:(接口返回zip压缩包流下载)