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 ?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.