Send a file with XmlHttpRequest: Streaming?(使用 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 的字符串,file 是 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 发送文件:流式传输?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 XmlHttpRequest 发送文件:流式传输?
基础教程推荐
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
