Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 647
Nika Kurashvili Avatar asked Sep 02 '25 16:09

Nika Kurashvili


2 Answers

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.

like image 150
Googlian Avatar answered Sep 05 '25 03:09

Googlian


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();
like image 29
wittier-banterer Avatar answered Sep 05 '25 03:09

wittier-banterer