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

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

问题描述

我正在尝试使用拖放功能上传大文件。我有这段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和文件是一个 Blob (根据 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发送文件:Streaming?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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