使用 XmlHttpRequest 发送文件:流式传输? [英] Send a file with XmlHttpRequest: Streaming?

查看:34
本文介绍了使用 XmlHttpRequest 发送文件:流式传输?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过拖放上传大文件.我有这段 Javascript 代码:

I am trying to upload big files with drag and drop. I have this piece of Javascript code:

xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('X-File-Name', file.name);
xhr.setRequestHeader('X-File-Size', file.size);
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);

其中 url 是目标 url 的字符串,fileBlob(根据 http://www.w3.org/TR/XMLHttpRequest2/#the-send-method) 我文件拖放后已检索.此代码适用于 Chrome 12、Safari 5 和 Firefox 4,并将文件的原始内容发送到 HTTP 请求的正文中.

where url is a string of the target url and file is a Blob (according to http://www.w3.org/TR/XMLHttpRequest2/#the-send-method) which I have retrieved after a file drag-drop. This code works in Chrome 12, Safari 5 and Firefox 4 and sends the raw contents of the file in the body of the HTTP request.

但是,如果文件足够大,则永远不会发送请求.相反,XMLHttpRequest 对象触发和错误事件(没有任何有用的消息).在我的环境中,此限制为 86Mb,但因机器而异.

However, if the file is big enough the request is never sent. Instead, the XMLHttpRequest object fires and error event (without any useful message). This limit is 86Mb in my environment, but it varies from machine to machine.

Chrome 的 javascript 控制台显示消息:

The javascript console of Chrome shows the message:

POST http://localhost/xfiles/xfiles.php undefined (undefined)

这与我的代码无关(它适用于较小的文件).

which has nothing to do with my code (which works perfectly with smaller files).

似乎浏览器在发送之前读取了内存中的整个文件.可能存在内存不足异常或类似的情况导致进程停止.无论如何,没有发送HTTP请求,因此可以肯定服务器的限制与此问题无关.

It seems that the browser reads the entire file in memory and before sending it. Probably there is an out of memory exception or something like that that stops the process. In any case, there no HTTP request is sent, so it is certain that the server's limits have nothing to do with this problem.

无论如何,读取整个文件是浪费资源.

有没有什么方法可以以流方式逐字节发送文件,而不必先将其存储在内存中?

Is there any method to send the file in a streaming fashion, byte by byte, without having to store it in the memory first?

推荐答案

尝试使用 Blob.slice 方法将 Blob 拆分为多个块,并将每个块作为单独的请求发送.

Try using the Blob.slice method to split the Blob up into multiple chunks, and send each one as a separate request.

这篇关于使用 XmlHttpRequest 发送文件:流式传输?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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