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

前端 未结 2 1978
不知归路
不知归路 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:42

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

提交回复
热议问题