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

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

如何從內容類型獲取 MIME 類型

如何從內容類型獲取 MIME 類型

30秒到達戰場 2021-11-12 15:26:21
問題是 axios 調用返回文件。有時是 xlsx,有時是純 txt。在javascript中,一旦我得到它們,我就強制通過blob下載它。像這樣的東西:var headers = response.headers;var blob = new Blob([response.data], {    type: headers['content-type']});var link = document.createElement('a');link.href = window.URL.createObjectURL(blob);link.download = "report.xlsx";link.click();正如你看到的,我有這樣的事情:link.download = "report.xlsx"。我想要的是用動態 mime 類型替換xlsx,以便有時是report.txt,有時是report.xlsx。我如何從內容類型做到這一點?
查看完整描述

2 回答

?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

您的應用程序的后端是什么?我在 C# (.NET Core) 中使用它來獲取文件的內容類型,然后將其設置為響應中的標頭:


public string GetContentType (string filePath) {

    var contentTypeProvider = new FileExtensionContentTypeProvider();

    string contentType;

    if( !contentTypeProvider.TryGetContentType( filePath, out contentType ) ) {

        contentType = "application/octet-stream";

    };

    return contentType;

}

編輯:修改 OP 代碼以動態處理內容類型:


var headers = response.headers;

var responseType = headers['content-type'];

var fileType = "text/plain";

var fileName = "report.txt";

if ( responseType == "application/octet-stream" ) {

    fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

    fileName = "report.xlsx";

}

var blob = new Blob([response.data], {

    type: fileType

});

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

link.href = window.URL.createObjectURL(blob);

link.download = fileName;

link.click();


查看完整回答
反對 回復 2021-11-12
?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

您可以使用標題的內容類型獲取文件擴展名。

使用這個 Javascript 庫 - node-mime


您只想傳遞您的headers['content-type'],它將為您提供需要為下載名稱設置的文件擴展名。


var ctype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";


console.log(mime.getExtension(ctype));

<script src="https://wzrd.in/standalone/mime@latest"></script>

示例:在您的情況下,


var headers = response.headers;

var blob = new Blob([response.data], {

    type: headers['content-type']

});

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

link.href = window.URL.createObjectURL(blob);

link.download = "report." + mime.getExtension(headers['content-type']);

link.click();

Mozilla 開發人員提供的 MIME 類型列表不完整。


查看完整回答
反對 回復 2021-11-12
  • 2 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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