2

我想将文件上传到远程设备。如果我查找与wireshark的连接,我会得到这个

POST /saveRestore.htm.cgi HTTP/1.1
Host: 10.128.115.214
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:15.0) Gecko/20100101 Firefox/15.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Referer: http://10.128.115.214/saveRestore.htm
Cache-Control: max-age=0
Content-Type: multipart/form-data; boundary=---------------------------961265085509552220604142744
Content-Length: 10708

-----------------------------961265085509552220604142744
Content-Disposition: form-data; name="restore"; filename="config(2).cfg"
Content-Type: application/octet-stream

现在这表示浏览器只接受 text/html,application/xhtml+xml,application/xml;q=0.9, / ;q=0.8

如果我用我的脚本上传文件,它会说

--0a7125aebb8845ba8ab9aa21306b01f6
Content-Disposition: form-data; name="restore"; filename="Config.cfg"
Content-Type: text/plain; charset=utf-8

所以这是一个错误的文件类型..

那么如何更改文件的内容类型?

到目前为止,我的代码如下所示:

#!/usr/bin/python

import httplib
import urllib2
from poster.encode import multipart_encode
import poster
from poster.streaminghttp import register_openers
register_openers()

params = {'restore': open("Config.cfg", "rb"), 'upload': 'PC ==>; Unit'}

datagen, headers = multipart_encode(params)

request = urllib2.Request('http://10.128.115.214/saveRestore.htm.cgi', datagen, headers)
u = urllib2.urlopen(request)
print u.read()
4

1 回答 1

2

在它的文档中poster.encode.MultipartParam说:

如果filetype设置,则用作此参数的 Content-Type。如果未设置,则默认为“text/plain; 字符集=utf8”</p>

因此,不要像这样指定参数:

params = {'restore': open("Config.cfg", "rb"), 'upload': 'PC ==>; Unit'}

像这样指定它们:

params = [MultipartParam('restore', open("Config.cfg", "rb"),
                         filetype = 'application/octet-stream'),
          ('upload', 'PC ==>; Unit')]
于 2012-10-01T19:11:41.237 回答