1. 程式人生 > >轉發:傳送post請求下載檔案

轉發:傳送post請求下載檔案

原文地址:https://blog.csdn.net/yunlala_/article/details/78385962

處理檔案流方案一

以下是我親試可以實現的一種方案:

這裡寫圖片描述

exportData () {
        const form = this.getSearchForm() // 要傳送到後臺的資料
        axios({ // 用axios傳送post請求
          method: 'post',
          url: '/user/12345', // 請求地址
          data: form, // 引數
          responseType: 'blob'
// 表明返回伺服器返回的資料型別 }) .then((res) => { // 處理返回的檔案流 const content = res const blob = new Blob([content]) const fileName = '測試表格123.xls' if ('download' in document.createElement('a')) { // 非IE下載 const elink = document.createElement('a'
) elink.download = fileName elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() URL.revokeObjectURL(elink.href) // 釋放URL 物件 document.body.removeChild(elink) } else
{ // IE10+下載 navigator.msSaveBlob(blob, fileName) } }) }

這裡用了Blob物件,上面的寫法就是用從伺服器接收到的檔案流(content-type:application/octet-stream)建立了一個blob物件,並使用該blob 建立一個指向型別陣列的URL,將該url作為a標籤的連結目標,然後去觸發a標籤的點選事件從而實現表格下載。