如何将javascript对象转换为实际文件,以便使用HTML5进行上传 [英] How to convert a javascript Object into an actual file in order to upload with HTML5

查看:92
本文介绍了如何将javascript对象转换为实际文件,以便使用HTML5进行上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大量数据的javascript对象,包括几个大的base64编码字符串。

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

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

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.

因此我们希望利用新的html5文件上传功能并实际测量数据上传到服务器的进度,以便在这个漫长的过程中为用户提供持续的反馈。

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.

为了使用此功能,这个大型阵列将具有作为实际文件而不是作为url params发送的巨大对象发送。

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.

有没有办法:

A。将此对象转换为实际文本文件并以此方式发送。

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

B.进入html5进度api并实际测量此标准ajax POST的进度。

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

提前致谢。

推荐答案

可以使用JavaScript对象( myData ),将其串行化为JSON,将其打包成mimetype JSON的Blob,并且使用HTML5上传API将其发送到服务器。您可以使用进度(在 progress 回调函数中)来更新HTML5进度条的值。

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

这篇关于如何将javascript对象转换为实际文件,以便使用HTML5进行上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆