2

I am writing JavaScript code to initiate a download of a file in the browser. I am able to get the bytes of the file in a string and I want to pass the string to a function that creates a file and initiates a download from it.

I have to avoid just storing the file on the server for someone to download through html like:

<a href="./some-file.pdf">file</a>

Here is the code I have so far which works just fine, but I need to modify the extension of the file to change it to match the data, which is the part I havn't figured out.

function download(data, filename = "aserc", type = ".txt") {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob)
    {
        window.navigator.msSaveOrOpenBlob(file, filename);
    } else  {
        var a = document.createElement("a"), url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

this will download a file but it will not be a .txt file. How do I change the type of the file using this code?

8
  • can you please try this , jsfiddle.net/UselessCode/qm5AG Commented Aug 21, 2017 at 4:50
  • @KrushnakantLadani thank you, I think that will work Commented Aug 21, 2017 at 4:54
  • blob type should be a MIME type, text/plain perhaps?, not a file extension ... filename should be aserc.txt Commented Aug 21, 2017 at 4:55
  • a.download = filename + type and add the required header Commented Aug 21, 2017 at 5:03
  • 1
    it's a binary file - so application/octet-stream Commented Aug 21, 2017 at 5:11

1 Answer 1

1

Add the file extension to the name of the file. Like this

a.download = filename + ".txt";

Looking at the docs the Blob object takes in 'plain/text' for the type attribute to specify text this may be something you should keep an eye on, change Blob declaration to

var file = new Blob([data], {type: 'plain/text'});
Sign up to request clarification or add additional context in comments.

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.