我有一个发送一些数据的 AJAX 请求。数据尊重 multipart/form-data specification .
我面临的问题是浏览器将 Content-Type header 设置为 text/plain,它应该是 multipart/form-data。
我试过这样做:request.setRequestHeader("Content-Type", "multipart/form-data");
但这给出了 400 Bad Request 错误。
如果我执行 request.setRequestHeader("Content-Typexxxx", "multipart/form-data");
没有错误,“Content-Typexxxx” header 已设置,但显然是对我没有帮助。
我想有一个可以设置的有效 Content-Type header 列表,“multipart/form-data”不在其中,但我找不到解决我的困境的方法。
实际发送的数据示例:
Content-Type: multipart/form-data; boundary=l3iPy71otz --l3iPy71otz Content-Disposition: form-data; name="titluPublic" Variation_1 --l3iPy71otz Content-Disposition: form-data; name="nr_versiune" --l3iPy71otz--
谢谢!
最佳答案
您没有在请求 header 中设置边界
,如下所示:
request.setRequestHeader("Content-Type", "multipart/form-data; boundary=l3iPy71otz");
有关详细信息,请参阅 RFC 2045 :
5 Content-Type Header Field
[…]
Parameters are modifiers of the media subtype, and as such do not fundamentally affect the nature of the content. The set of meaningful parameters depends on the media type and subtype. Most parameters are associated with a single specific subtype. However, a given top-level media type may define parameters which are applicable to any subtype of that type. Parameters may be required by their defining content type or subtype or they may be optional. MIME implementations must ignore any parameters whose names they do not recognize.For example, the "charset" parameter is applicable to any subtype of "text", while the "boundary" parameter is required for any subtype of the "multipart" media type.
更新:我发现的另一个问题on the net当 charset
添加到请求 header 中的 Content-type
时出现,但不会出现在正文的消息边界中(这对于您的测试用例也是如此)。这似乎不是一个可能的解决方案,但也许会有所帮助。
在您的情况下,显式将 charset
添加到请求 header 和消息边界中:
data.params += "--" + data.uniqid + "; charset=UTF-8" + data.crlf;
…
request.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + data.uniqid + "; charset=UTF-8");
更新 2: 自己在本地尝试后,我注意到前导边界未被识别,而是被解释为最后一个参数内容(在我更宽容的服务器上)。也许这导致 Apache 抛出 400 Bad Request
错误。
经过反复试验,我注意到这是因为服务器期望 charset
位于每个 边界,甚至是最后一个边界。为了防止混淆,我决定在边界参数之前在请求 header 中显式设置charset
,这样边界将是Content-中的最后一个参数type
请求 header 。在此之后,一切似乎都运行良好。
data.params = "Content-Type: multipart/form-data; boundary=" + data.uniqid;
…
data.params += "--" + data.uniqid + data.crlf;
…
data.params += "--" + data.uniqid + "--";
…
request.setRequestHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + data.uniqid);
关于javascript - 在 XHR 中使用 multipart/form-data 作为 Content-Type 时获取 '400 Bad Request',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4773725/