2

I have a query regarding file operations using JavaScript-

Scenario - My JS function calls a wcf service which returns the file content in the form of byte array or stream and the mime type. This byte array/stream needs to be converted to a file and which will be downloaded on user's machine.
Reference code -

var arr = "This is test content";
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');

a.href = window.URL.createObjectURL(new Blob([byteArray], {
    type: 'text/plain'
}));
a.download = "Test";

document.body.appendChild(a);
a.click();

document.body.removeChild(a);

The code works for only text files. Files with mime type other than text are corrupted. I understand that file operations are severly restricted at client side, but just to confirm - Is there anyway to convert byte array/stream to files such as Word,Excel, PDF and etc ?

Community
  • 1
  • 1
Thomas Mathew
  • 1,151
  • 6
  • 15
  • 30
  • Similar question here: http://stackoverflow.com/questions/27946228/file-download-a-byte-array-as-a-file-in-javascript-extjs – Akhoy Oct 14 '15 at 12:38
  • @Akhoy Thanks. Same URL as the reference code. As i said, text files are working but not word or pdf. – Thomas Mathew Oct 15 '15 at 03:41
  • How to do this on .NET C#? I need to convert a File MIMEType octet-stream (format bytestream) to a excel is it possible too? – AbbathCL Aug 26 '21 at 23:26

1 Answers1

2

I accomplish a similar goal with this. Pick up from where you have your byteArray, and try this:

    var byteArray = new Uint8Array(arrayBuffer);
    var a = window.document.createElement('a');   
    a.href = window.URL.createObjectURL(new Blob([byteArray], { type:'application/octet-stream' }));

    // supply your own fileName here...
    a.download = "YourFileName.XLSX";

    document.body.appendChild(a)
    a.click();
    document.body.removeChild(a)

Setting contentType to "application/octet-stream" will accommodate any binary file type.

Community
  • 1
  • 1
KWallace
  • 624
  • 7
  • 15
  • This seems dangerous, btw. Basically, you could **force** a file to download to a remote computer, even if it only lands in their browser downloads folder. You are creating a download link, then clicking on it. I wonder why this isn't stopped by modern browsers? – KWallace Oct 07 '18 at 20:47