图像加载后 MultiValueDict 为空

MultiValueDict is empty when image has loaded

我正在尝试模拟浏览器工作。当我从浏览器发送图像时,我进入 request.FILES that

<MultiValueDict: {u'file': [<InMemoryUploadedFile: 1.jpg (image/jpeg)>]}>

如果我从后端发送图像 POST 请求:

import httplib
conn = httplib.HTTPConnection(HOST, PORT)
headers = {"Content-type": "application/x-www-form-urlencoded",      "Accept": 'text/plain', 
"Cookie": cookies, 'X_REQUESTED_WITH': 'XMLHttpRequest'}
conn.request("POST", "/upload/%s" % storyId, open("pictures/1.jpg"), headers)
response = conn.getresponse()  

我得到:

<MultiValueDict: {}>

怎么了?

当您从浏览器发送文件时,Content Type header 是multipart/form-data;不是 application/x-www-form-urlencoded 当您发送文件时,请求中还有其他更改。看一下,这是从浏览器发送文件时请求 headers 的样子。

POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L
<other headers>

------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"

100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object

<file data>
------WebKitFormBoundaryePkpFF7tjBAqx29L--

您可以在此处阅读更多内容 Whosebug answer

也就是说,您 "simulating" 浏览器文件请求不正确。