XMLHttpRequest POST 多部分/表单数据

2022-01-15 00:00:00 xmlhttprequest javascript ajax

我想在 JavaScript 中使用 XMLHttpRequest 来发布一个包含文件类型输入元素的表单,这样我就可以避免页面刷新并返回有用的 XML.

I want to use XMLHttpRequest in JavaScript to POST a form that includes a file type input element so that I can avoid page refresh and get useful XML back.

我可以在不刷新页面的情况下提交表单,使用 JavaScript 将表单上的目标属性设置为 MSIE 的 iframe 或 Mozilla 的对象,但这有两个问题.小问题是目标不符合 W3C(这就是我在 JavaScript 中设置它的原因,而不是在 XHTML 中).主要问题是 onload 事件不会触发,至少在 OS X Leopard 上的 Mozilla 上不会.此外,XMLHttpRequest 会做出更漂亮的响应代码,因为返回的数据可以是 XML,而不是像 iframe 那样仅限于 XHTML.

I can submit the form without page refresh, using JavaScript to set the target attribute on the form to an iframe for MSIE or an object for Mozilla, but this has two problems. The minor problem is that target is not W3C compliant (which is why I set it in JavaScript, not in XHTML). The major problem is that the onload event doesn't fire, at least not on Mozilla on OS X Leopard. Besides, XMLHttpRequest would make for prettier response code because the returned data could be XML, not confined to XHTML as is the case with iframe.

提交表单会产生如下所示的 HTTP:

Submitting the form results in HTTP that looks like:

Content-Type: multipart/form-data;boundary=<boundary string>
Content-Length: <length>
--<boundary string>
Content-Disposition: form-data, name="<input element name>"

<input element value>
--<boundary string>
Content-Disposition: form-data, name=<input element name>"; filename="<input element value>"
Content-Type: application/octet-stream

<element body>

如何获取 XMLHttpRequest 对象的 send 方法来复制上述 HTTP 流?

How do I get the XMLHttpRequest object's send method to duplicate the above HTTP stream?

推荐答案

您可以自己构造 'multipart/form-data' 请求(在 http://www.faqs.org/rfcs/rfc2388.html) 然后使用 send 方法(即 xhr.send(your-multipart-form-data)).同样,但更简单的是,在 Firefox 4+(也在 Chrome 5+ 和 Safari 5+)中,您可以使用 FormData 接口,有助于构建此类请求.send 方法适用于文本内容,但如果要发送图像等二进制数据,可以借助已经开始的 sendAsBinary 方法来完成使用 Firefox 3.0.关于如何通过XMLHttpRequest发送文件的详细信息,请参考http://blog.igstan.ro/2009/01/pure-javascript-file-upload.html.

You can construct the 'multipart/form-data' request yourself (read more about it at http://www.faqs.org/rfcs/rfc2388.html) and then use the send method (ie. xhr.send(your-multipart-form-data)). Similarly, but easier, in Firefox 4+ (also in Chrome 5+ and Safari 5+) you can use the FormData interface that helps to construct such requests. The send method is good for text content but if you want to send binary data such as images, you can do it with the help of the sendAsBinary method that has been around starting with Firefox 3.0. For details on how to send files via XMLHttpRequest, please refer to http://blog.igstan.ro/2009/01/pure-javascript-file-upload.html.

相关文章