Saving Binary Data as File Using JavaScript from a Browser

Saving binary data as file using JavaScript from a browser

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, name) {
var blob = new Blob(data, {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
};
}());

saveByteArray([sampleBytes], 'example.txt');



JSFiddle: http://jsfiddle.net/VB59f/2

How to use crypto-js to save the binary data, of an encryption-output, to a file?

CryptoJS.AES.encrypt() returns a CipherParams object that encapsulates, among others, the ciphertext as WordArray. One possibility is to convert this WordArray to a Uint8Array with a custom method. In the following code this conversion is done by convertWordArrayToUint8Array():

function convertWordArrayToUint8Array(wordArray) {
var arrayOfWords = wordArray.hasOwnProperty("words") ? wordArray.words : [];
var length = wordArray.hasOwnProperty("sigBytes") ? wordArray.sigBytes : arrayOfWords.length * 4;
var uInt8Array = new Uint8Array(length), index=0, word, i;
for (i=0; i<length; i++) {
word = arrayOfWords[i];
uInt8Array[index++] = word >> 24;
uInt8Array[index++] = (word >> 16) & 0xff;
uInt8Array[index++] = (word >> 8) & 0xff;
uInt8Array[index++] = word & 0xff;
}
return uInt8Array;
}

var AES_KEY = CryptoJS.enc.Utf8.parse('0123456789012345');
var AES_IV = CryptoJS.enc.Utf8.parse('5432109876543210');
var plaintext = 'The quick brown fox jumps over the lazy dog';
var ciphertextCP = CryptoJS.AES.encrypt(plaintext, AES_KEY, { iv: AES_IV }); // CipherParams object
var ciphertextWA = ciphertextCP.ciphertext; // WordArray
var ciphertextArr = convertWordArrayToUint8Array(ciphertextWA); // Uint8Array

This Uint8Array can now be stored in a file, e.g. with:

var fileName = "encdata.bin";
saveByteArray([ciphertextArr], fileName);

using saveByteArray() from here.


Another approach is to convert the WordArray to a binary string using the Latin1 encoder:

var ciphertextBinStr = ciphertextWA.toString(CryptoJS.enc.Latin1);

which can then easily be converted to a Uint8Array, e.g. with:

function str2Uint8Array(str) {
const arr = new Uint8Array(new ArrayBuffer(str.length));
for (let i = 0, strLen = str.length; i < strLen; i++)
arr[i] = str.charCodeAt(i);
return arr;
}

var ciphertextArr = str2Uint8Array(ciphertextBinStr);

How to save a text to file and read it again but save as binary in javascript

Edit, Updated

write file

let byteChars = atob("my string");
let byteNumbers = new Array(byteChars.length);
for (var i = 0; i < byteChars.length; i++) {
byteNumbers[i] = byteChars.charCodeAt(i);
}
let byteArray = new Uint8Array(byteNumbers);
var data = new Blob([byteArray], {type: "application/octet-stream"});
saveAs(data, "myfile.abc");

read file

<input type="file">
<script>
var reader = new FileReader();
reader.addEventListener("load", function(e) {
document.body.innerHTML += "<br>" + btoa(e.target.result);
});
document.querySelector("input[type=file]")
.addEventListener("change", function(e) {
reader.readAsBinaryString(e.target.files[0])
})
</script>

plnkr http://plnkr.co/edit/0KVhXnd0JpysplDLcAlC?p=preview


You can use TextEncoder(), TextDecoder() or FileReader(), .readAsBinaryString()

var str = "my string";var encoder = new TextEncoder();var encodedBytes = encoder.encode(str);// do file save stuffvar decoder = new TextDecoder();var decodedBytes = decoder.decode(encodedBytes);
console.log(encodedBytes, decodedBytes);
// alternatively, using `FileReader()`var reader = new FileReader();reader.onload = function() { console.log("FileReader result:", reader.result)}reader.readAsBinaryString(new Blob([encodedBytes]))

Using HTML5/JavaScript to generate and save a file

OK, creating a data:URI definitely does the trick for me, thanks to Matthew and Dennkster pointing that option out! Here is basically how I do it:

1) get all the content into a string called "content" (e.g. by creating it there initially or by reading innerHTML of the tag of an already built page).

2) Build the data URI:

uriContent = "data:application/octet-stream," + encodeURIComponent(content);

There will be length limitations depending on browser type etc., but e.g. Firefox 3.6.12 works until at least 256k. Encoding in Base64 instead using encodeURIComponent might make things more efficient, but for me that was ok.

3) open a new window and "redirect" it to this URI prompts for a download location of my JavaScript generated page:

newWindow = window.open(uriContent, 'neuesDokument');

That's it.

Download Binary Files with Javascript

Have a look at the MDN article on XMLHttpRequest.

If you set the response of the XMLHttpRequest to ArrayBuffer you could do the following:

var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "arraybuffer";

xhr.onload = function () {
if (this.status === 200) {
var blob = new Blob([xhr.response], {type: "application/pdf"});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
};
xhr.send();

Option 2:

You could use Blob as the response of the XMLHttpRequest. And then maybe save it in the FileSystem (FileSystem API)

It may look like:

var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";

xhr.onload = function () {
onDownloaded(this);
};
xhr.send();

Option 3:

If you only want to download and "show" images you can easily do this like so:

var img = new Image();

// add the onload event before setting the src
img.onload = function() {
onImageDownloaded(img);
}

// start the download by setting the src property
img.src = requestUrl


Related Topics



Leave a reply



Submit