4

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?

1
  • Damn, i wish someone had answered this one - i'll try get back here if I find a solution to my problem. I was looking for a way to make a custom format to store the smallest picture ever, like this: delimiter, x1y1x2y2x3y3x4y4 delimiter x1xy2 etc, such that the delimiters denote swapping to the next color and the palette is stored seperately Commented Sep 4, 2018 at 23:11

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Its not working,still I am getting plain text document (text/plain)
How do we save it with extension .foo or .bar, or any unknown extension that has no known mime type? EDIT: looks like by providing an unknown mime type, you can provide any extension in the file name for the a.download of the <a> element used for download.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.