简体   繁体   English

如何将 JavaScript 对象转换为实际文件以便使用 HTML5 上传

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

I have a JavaScript object with a huge amount of data in it, including several large base64 encoded strings.我有一个包含大量数据的 JavaScript 对象,包括几个大的 base64 编码字符串。

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.我们目前正在通过一个简单的 ajax POST 将数据发送到服务器,但由于数据太大,用户的等待时间是不可接受的。

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.出于这个原因,我们希望利用新的 html5 文件上传功能,并在数据上传到服务器时实际测量进度,以便在这个漫长的过程中为用户提供持续的反馈。

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.为了使用这个特性,这个大数组必须作为一个实际的文件发送,而不是作为一个巨大的对象作为 url 参数发送。

Is there any way to either:有没有办法:

A. Convert this object into an actual text file and send it that way. A. 将此对象转换为实际的文本文件并以这种方式发送。

or要么

B. Hook into the html5 progress api and actually measure the progress of this standard ajax POST. B、钩入html5的progress api,实际测量这个标准ajax POST的进度。

Thanks in advance.提前致谢。

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.可以采用 JavaScript 对象 ( myData ),将其字符串化为 JSON,将其打包为 mimetype JSON 的 Blob,然后使用 HTML5 上传 API 将其发送到服务器。 You can use the progress (in the progress callback function) to update the value of an HTML5 progress bar.您可以使用进度(在progress回调函数中)来更新 HTML5 进度条的值。

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

Convert to Blob object or File object, then append to FormData , and use xhr or fetch to send to server.转换为Blob对象或File对象,然后附加到FormData ,并使用xhrfetch发送到服务器。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM