0

I am using the following code to create a text file from the browser. It works when I'm using data:text/plain;charset=utf-8, and the text is plain but when the data is xls, I get a network error and it doesn't work. Can anyone advise me what I'm missing or doing wrong.

function download(filename, text) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:application/xls;base64,'+text);
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    console.log(text);

    document.body.removeChild(element);
    }

I should note, the code has come from https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server

Thanks in advance.

I don't want to use BLOBS.

2
  • Is your text correct base64-encoded XLS? Commented Oct 10, 2019 at 15:24
  • 1
    I think your content type is wrong. Try this: stackoverflow.com/questions/2937465/… Commented Oct 10, 2019 at 15:26

1 Answer 1

1

There is no type as application/xls https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types

Complete IANA List : [ https://www.iana.org/assignments/media-types/media-types.xhtml#application ]

Read this answer : What is correct content-type for excel files?

For BIFF .xls files

application/vnd.ms-excel

For Excel2007 and above .xlsx files

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Sign up to request clarification or add additional context in comments.

6 Comments

I change the href to element.setAttribute('href', 'data:application/vnd.ms-excel;base64,'+text); but didn't seem to do any good :( unless I've misunderstood what to do.
what is the text?
It is definately a XLS file that i'm trying to download.
is it base64 encoded ? if not why are you appending base64 before the text as in your comment ?
Ok, I'm getting somewhere now, thx. I assumed it was base64, I've removed it and now its downloading but only 2KB, should be much bigger.
|

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.