Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom file type and extension using Blob()

Tags:

javascript

function download(){
  var fileName = 'testDemo';
  var type = 'xyz';
  var data = 'Hello world';
  var file = new Blob([data], {
    type: type
  });
  if (window.navigator.msSaveOrOpenBlob) // IE10+
    window.navigator.msSaveOrOpenBlob(file, fileName);
  else { // Others
    var a = document.createElement("a"),
      url = URL.createObjectURL(file);
    a.href = url;
    a.download = fileName + '.' +type;
    document.body.appendChild(a);
    a.click();
    setTimeout(function() {
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    }, 100);
  }
}
<button onclick='download()'>Download</button>

Here I am setting type and extension as .xyz but still it shows plain text document (text/plain) in property and can't read the file type also which shows a empty string. How can I create a custom extension and type?

like image 945
Omaim Avatar asked Nov 15 '25 22:11

Omaim


2 Answers

You are passing an extension instead of useful mime type at the time of instantiating blob object.

 var fileName = 'testDemo';
 var type = 'application/pdf';
 var data = 'Hello world';
 var file = new Blob([data], {
            type: type
           });

Refer other useful mime types here : mime types

like image 125
Rajat Badjatya Avatar answered Nov 17 '25 22:11

Rajat Badjatya


Most MIME types refer to a specific file extension, so by using a less-specific mime type, such as application/octet-stream, you can guide the browser to get it's file type from your a.download = fileName + '.' +type;. I've tested it and it works for text files with custom extensions.

See the IANA list of MIME types.

So your variables would look like this:

var fileName = 'testDemo';
var mimeType = 'application/octet-stream';
var type = 'xyz';
var data = 'Hello world';
var file = new Blob([data], {
  type: mimeType
});
like image 41
SP4CEBAR Avatar answered Nov 17 '25 20:11

SP4CEBAR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!