我在尝试将文件发布到服务器时遇到问题。我试图将文件上传脚本发送到服务器,此服务器对请求后的正确性非常敏感'
我调试了将文件发送到服务器的页面,浏览器发送了这个文本(TextView):
POST http://example.com/post HTTP/1.1
Host: example.com
Connection: keep-alive
Content-Length: 20625
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarykGHBkXoER9gNuVna
Referer: http://example.com/foo
Accept-Encoding: gzip, deflate
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4,pt;q=0.2
------WebKitFormBoundarykGHBkXoER9gNuVna
Content-Disposition: form-data; name="files[]"; filename="file.zip"
Content-Type: application/octet-stream
...raw file data...
------WebKitFormBoundarykGHBkXoER9gNuVna--
但是,我的脚本正在发送它(TextView):
POST http://example.com/post HTTP/1.1
Host: example.com
Connection: keep-alive
Accept-Encoding: gzip, deflate
Accept: */*
User-Agent: python-requests/2.18.1
Content-Length: 20604
--f8c266cf436941019c5a80c7d4779a57
Content-Disposition: form-data; name="files[]"; filename="file.zip"
Content-Type: application/zip
...raw file data...
--f8c266cf436941019c5a80c7d4779a57--
在服务器上出现原因错误时,请注意:当我将files=files
更改为data=files
当前代码:
files = MultipartEncoder({'files[]': (filename, open(local_path,'rb'), mimetype)})
UploadFile = requests.post(self.UploadURL, data=files, allow_redirects=False)
工作代码:
files = {'files[]': (filename, open(local_path,'rb'), mimetype)}
UploadFile = requests.post(self.UploadURL, files=files, allow_redirects=False)
我使用MultipartEncoder
来发送大量文件。
我发现最大的不匹配是"边界",但为什么这个'边界'正在working code
中生成,但在Current code
中却没有?
如何解决这个问题?
答案 0 :(得分:0)
您没有设置Content-Type
标题,MultipartEncoder
为您提供:
files = MultipartEncoder({'files[]': (filename, open(local_path,'rb'), mimetype)})
UploadFile = requests.post(
self.UploadURL, data=files, allow_redirects=False,
headers={'Content-Type': files.content_type})
标头必须来自多部分编码,因为它负责选择用于在多部分响应中删除各种MIME部分的边界。在您的上传中:
--f8c266cf436941019c5a80c7d4779a57
但每次代码运行时都会随机生成。提供的标题如下所示:
Content-Type: multipart/form-data; boundary=--f8c266cf436941019c5a80c7d4779a57