Saving Uint8Array to binary

I am working on a web application that opens binary files and allows editing them.

This process is basically ondrop -> dataTransfer.files[0] -> FileReader -> Uint8Array

Essentially, I want to save the modified file back as a binary file. Ideal as downloading a file with the specified file name.

There seems to be no standard method for this, and that sucks because everything up to this point is well supported.

I am currently converting an array to a string using String.fromCharCode() , base64 encodings and using the uri of the data in the hyperlink, e.g. data:application/octet-stream;base64,.. , along with the download attribute to indicate the file name.

This seems to work, but it's pretty hacky, and I think converting raw bytes to strings can lead to encoding problems depending on the byte values. I do not want the data to become corrupted or break the line.

If this is not the case, is there a better / correct method for getting an array of bytes as a binary for the user?

+7
javascript cross-browser binary-data file-io typed-arrays
source share
1 answer

These are the utilities that I use to upload files to a cross browser. The great thing is that you can actually set the download property of the link to the name in which you want your file name to be.

FYI mimeType for application/octet-stream binary

 var downloadBlob, downloadURL; downloadBlob = function(data, fileName, mimeType) { var blob, url; blob = new Blob([data], { type: mimeType }); url = window.URL.createObjectURL(blob); downloadURL(url, fileName, mimeType); setTimeout(function() { return window.URL.revokeObjectURL(url); }, 1000); }; downloadURL = function(data, fileName) { var a; a = document.createElement('a'); a.href = data; a.download = fileName; document.body.appendChild(a); a.style = 'display: none'; a.click(); a.remove(); }; 

Using:

 downloadBlob(myBinaryBlob, 'some-file.bin', 'application/octet-stream'); 
+6
source share

All Articles