亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從響應中讀取文件名-reactJs

如何從響應中讀取文件名-reactJs

C#
烙印99 2023-09-16 15:08:37
我正在從服務器下載文件。我在那里設置一個我想在前端讀取的文件名。這是我在服務器上執行此操作的方法:string fileName = "SomeText" + DateTime.UtcNow.ToString() + ".csv";return File(stream, "text/csv", fileName);基本上我會返回不同類型的文件,有時csv有時xlsx有時pdf。所以我想在前端獲取文件名,以便我可以將其保存為應有的格式,例如SomeText.pdf它將自動保存在本地計算機上作為pdf.這是我的前端代碼:getFileFromServer(params).then(response => {  console.log('server response download:', response);  const type = response.headers['content-type'];  const blob = new Blob([response.data], { type: type, encoding: 'UTF-8' });  //const url = window.URL.createObjectURL(blob);  const link = document.createElement('a');  link.href = window.URL.createObjectURL(blob);  link.download = 'file.xlsx'; // Here I want to get rid of hardcoded value instead I want filename from server  link.click();  link.remove(); //  Probably needed to remove html element after downloading?});我在“響應標頭”下的“網絡”選項卡中看到有一個Content-Disposition包含該信息的:Content-Disposition: attachment; filename="SomeText22/08/2019 10:42:04.csv";但我不知道它在我的回復中是否可用,以及如何在我的前端部分中讀取它,以便我可以替換link.download = 'file.xlsx';來自服務器的路徑..非常感謝大家
查看完整描述

3 回答

?
梵蒂岡之花

TA貢獻1900條經驗 獲得超5個贊

這是一種特殊類型的標頭,因此要在前端獲取此標頭,后端人員應該允許從他的一端。然后你可以在響應中的標題


response.headers.get("content-disposition")

我在我的項目中使用了以下代碼


 downloadReport(url, data) {

    fetch("url of api")

      .then(async response => {

        const filename = response.headers

          .get("content-disposition")

          .split('"')[1];

        const text = await response.text();

        return { filename, text };

      })

      .then(responseText => this.download(responseText))

      .catch(error => {

        messageNotification("error", error.message);

        throw new Error(error.message);

      });

  }


查看完整回答
反對 回復 2023-09-16
?
藍山帝景

TA貢獻1843條經驗 獲得超7個贊

要從客戶端(前端)的 Content-Disposition 獲取文件名,您必須從服務器端(后端)授予權限。Spring用戶可以使用


@CrossOrigin(value = {"*"}, exposedHeaders = {"Content-Disposition"})

@Controller

@RequestMapping("some endpoint")

在他們的控制器類中。


然后從前端我們可以使用獲取文件名。


const filename = response.headers['content-disposition'].split('filename=')[1];

希望這可以幫助。上述解決方案對我來說效果很好


查看完整回答
反對 回復 2023-09-16
?
婷婷同學_

TA貢獻1844條經驗 獲得超8個贊

您可以通過這種方式filename從header 獲取Content-Disposition


getFileFromServer(params).then(response => {

  // your old code

  const [, filename] = response.headers['content-disposition'].split('filename=');

  const link = document.createElement('a');

  link.download = filename;

  // your old code

});

希望這會有所幫助


查看完整回答
反對 回復 2023-09-16
  • 3 回答
  • 0 關注
  • 200 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號