首页 > 解决方案 > how to get mime type from content-type

问题描述

The thing is axios calls return files. sometimes xlsx, sometimes plain txt.

In javascript, as soon as I get them, i force download it via blob.

Something like this:

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();

As you see, I got something like this: link.download = "report.xlsx" . What I want is to replace xlsx with dynamic mime type so that sometimes it's report.txt and sometimes it's report.xlsx.

How do I do that from content-type?

标签: javascriptapiaxios

解决方案


您的应用程序的后端是什么?我在 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();

推荐阅读