我想将文件上传到Web服务器。从我读过的,最好的方法是在HTTP POST请求上使用multipart/form-data编码类型。Python - HTTP multipart/form-data POST请求
我的研究似乎表明,没有简单的方法来使用Python标准库来完成此操作。我使用Python 3
(注:看到一个名为requests(PyPI Link)来轻松地完成这个包)
我目前使用这种方法:
import mimetypes, http.client
boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T' # Randomly generated
for fileName in fileList:
# Add boundary and header
dataList.append('--' + boundary)
dataList.append('Content-Disposition: form-data; name={0}; filename={0}'.format(fileName))
fileType = mimetypes.guess_type(fileName)[0] or 'application/octet-stream'
dataList.append('Content-Type: {}'.format(fileType))
dataList.append('')
with open(fileName) as f:
# Bad for large files
dataList.append(f.read())
dataList.append('--'+boundary+'--')
dataList.append('')
contentType = 'multipart/form-data; boundary={}'.format(boundary)
body = '\r\n'.join(dataList)
headers = {'Content-type': contentType}
conn = http.client.HTTPConnection('http://...')
req = conn.request('POST', '/test/', body, headers)
print(conn.getresponse().read())
本工程以发送文本。
有两个问题:这只是文本,整个文本文件必须作为一个巨大的字符串存储在内存中。
如何上传任何二进制文件?有没有办法做到这一点,而无需将整个文件读入内存?
你应该使用你已经提到的请求包。有很多东西不是由标准库处理的,比如会话管理,认证,检查SSL证书......你不使用请求模块的原因是什么? – Achim
您可以将代码从请求模块中复制出来,然后执行您所需的操作。 – User
这当然是你的决定。但是如果我可以选择打包高质量,经过充分测试的“使命证明”,......图书馆或我自己的自定义代码,我总是会选择第一个。 ;-) – Achim