[C#] Asp.net mvc 搭配 axios下載檔案


Posted by mike-hsieh on 2023-09-20

在 .net framework mvc 中,常會使用到下載檔案,且有錯誤需要顯示錯誤訊息等等,那簡單紀錄一下實作內容。

內容要點:

  1. 後端為 .net framework mvc
  2. View中使用axios,呼叫後端
  3. 檔案須不限制類型,由檔案後綴自行決定
  4. 若發生錯誤,錯誤訊息須以json顯示

以下為後端的代碼:

 [HttpPost]
 public ActionResult DownloadFile(object data)
 {
     try
     {
         //  取得檔案,為byte[]
         var file = _service.GeneratePdf(data);

         //  byte to stream
         MemoryStream pdfStream = new MemoryStream(file);

         //  return FileStreamResult
         return new FileStreamResult(pdfStream, "application/octet-stream");
     }
     catch (Exception ex)
     {
         //  有錯誤回傳Json錯誤資訊
         return Json(new { data = ex });
     }
 }

以下為頁面端的axios代碼:

axios.post(
    'Home/DownloadFile',
    {
        data: row.data
    },
    {
        'responseType': 'blob',
        'Content-Type': 'application/json',
    },
).then(resp => {
    //  下載檔案,且檔名後綴就是檔案類型,例如: 123.pdf, 456.xsxl, 789.zip
    const pdfBlob = new Blob([resp.data], { type: 'application/octet-stream' });
    const pdfUrl = URL.createObjectURL(pdfBlob);
    const downloadLink = document.createElement('a');
    downloadLink.href = pdfUrl;
    downloadLink.download = '123.pdf';  // 下載文件名稱。(123.pdf, 456.xsxl, 789.zip)
    downloadLink.textContent = 'downloadFile';  //a標籤的文字(不會顯示)
    document.body.appendChild(downloadLink);
    downloadLink.click();
    URL.revokeObjectURL(pdfUrl);
}).catch(err => {
    if (err.response) {
        //  由於axios定義回傳格式是Blob,但是後端實際回傳的是Json,所以用FileReader將Blob轉換為Json
        const reader = new FileReader();
        reader.readAsText(err.response.data);
        reader.onload = function (event) {
            console.log(JSON.parse(reader.result));  // 這邊處理錯誤訊息的顯示
        }
    } else if (err.request) {
        console.error(err.request);
    } else {
        console.error('Error', err.message);
    }
})

#Axios #ASP.NET MVC #download file #error message #JSON #ajax







Related Posts

redis 套件的 Property 'on' does not exist on type 'RedisClientType'

redis 套件的 Property 'on' does not exist on type 'RedisClientType'

Command Line相關

Command Line相關

HTML CSS position 屬性

HTML CSS position 屬性


Comments