How to convert a JavaScript Object into an actual file in order to upload with HTML5

前端 未结 2 1989
不知归路
不知归路 2020-12-24 09: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 si

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-24 09:36

    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);
    

提交回复
热议问题