17

I have a JavaScript object with a huge amount of data in it, including several large base64 encoded strings.

We are currently sending the data to the server via a simple ajax POST but since the data is so large the wait time for the user is unacceptable.

For this reason we wish to harness the new html5 file upload features and actually measure the progress as the data is uploaded to the server so that the user is provided with constant feedback during this lengthy process.

In order to use this feature this large array will have to be sent as an actual file rather than as a huge object sent as url params.

Is there any way to either:

A. Convert this object into an actual text file and send it that way.

or

B. Hook into the html5 progress api and actually measure the progress of this standard ajax POST.

Thanks in advance.

isherwood
  • 58,414
  • 16
  • 114
  • 157
gordyr
  • 6,078
  • 14
  • 65
  • 123
  • POST vs. upload will not have a significant speed difference. All you will gain is a progress bar. – Diodeus - James MacFarlane Jan 03 '13 at 22:15
  • 1
    Indeed, I should have been clearer. I understand we won't see any speed difference, it is purely the progress bar that we are after in order to provide user feedback during this lengthy progress. I have edited my question to reflect this. – gordyr Jan 03 '13 at 22:16

2 Answers2

20

It's possible to take a JavaScript object (myData), stringify it into JSON, pack that into a Blob of mimetype JSON, and send that to the server with the HTML5 upload API. You can use the progress (in the progress callback function) to update the value of an HTML5 progress bar.

var myData = {
    data1: "Huge amount of data",
    data2: "More very large data"
};

var xhr = new XMLHttpRequest();

xhr.upload.addEventListener('progress', function (e) {
    console.log(100*(e.loaded / e.total) + '%');
}, false);

xhr.open('POST', 'url', true);

var data = new FormData();
data.append('file', new Blob([JSON.stringify(myData)],{type:'application/json'}));
xhr.send(data);
fuzic
  • 2,492
  • 16
  • 22
2

Convert to Blob object or File object, then append to FormData, and use xhr or fetch to send to server.

var data = 'some data'; //string, arrary buffer, typed array, blob, ...
var filename01 = 'abc.txt', filename02 = 'efg.txt';
var type = 'text/plain';
var fd = new FormData();

//use file object
var file = new File([data], filename01, {type:type}); //add filename here
fd.append('file01', file);

//use blob object
var blob = new Blob([data], {type:type});
fd.append('file02', blob, filename02); //add filename by append method

fetch('/server.php', {method:'POST', body:fd})
.then(function(res){
    return res.text();
})
.then(console.log)
.catch(console.error)
;
Alfonso Rubalcava
  • 2,237
  • 17
  • 26
cuixiping
  • 24,167
  • 8
  • 82
  • 93