简体   繁体   中英

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?

What is the backend of your application? I used this in C# (.NET Core) to get the content type of a file then set it as a header in the response:

public string GetContentType (string filePath) {
    var contentTypeProvider = new FileExtensionContentTypeProvider();
    string contentType;
    if( !contentTypeProvider.TryGetContentType( filePath, out contentType ) ) {
        contentType = "application/octet-stream";
    };
    return contentType;
}

Edit: modified OP code to handle content type dynamically:

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

You can get the file extension using the content type of headers.
Use this Javascript library - node-mime

You just want to pass your headers['content-type'] , it will give you the file extension which you need to set for download name.

 var ctype = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; console.log(mime.getExtension(ctype));
 <script src="https://wzrd.in/standalone/mime@latest"></script>

Example: In your case,

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

Incomplete list of MIME types from Mozilla Developers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM