narusawa narusawa - 5 months ago 10
JSON Question

JSONifying a Blob file

I am trying to JSONify a blob file so that I can send it over AJAX requests. I have tried with the code below without any success. When I parse a JSONified file, I only get a different file with much smaller size.

function test(blob, cb) {

var fileReader = new FileReader()
fileReader.readAsArrayBuffer(blob)
fileReader.onloadend = function() {

// client
var arry = Array.from(new Uint8Array(fileReader.result))
var data = {data: arry }
var json = JSON.stringify(data)

// server
var parse = JSON.parse(json)
var arr = parse.data.buffer
var blob = new Blob([arr])
}
}

Answer

You can try to use FileReader.readAsDataURL() method, and send the data as base64 encoded string, and than decode it on the server side. Base64 string will be much smaller than json string representing an array.

Here is an example

function getBase64() {
  var file = document.querySelector('input[type=file]').files[0];
  var reader = new FileReader();
  reader.addEventListener("load", function () {
  	document.getElementById("result").value = reader.result;
  }, false);
  
  if (file) {
    reader.readAsDataURL(file);
  }
}
<input type="file" onchange="getBase64()" />
<br/>
<textarea id="result"></textarea>

Comments