2012-10-01 73 views
1

我想将文件上传到远程设备。 如果我看到了Wireshark的连接我得到这个如何更改内容类型Python

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的,应用/ 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() 
+0

可能重复(海报)](http://stackoverflow.com/questions/12669274/wrong-content-type-when-transfering-file-with-python-poster) –

+0

这是完全不清楚。什么是服务器和什么是客户端,你在哪里设置内容类型/处置? – njzk2

+0

服务器是10.128.115.214 saveRestore.htm.cgi是一个用于上传和恢复文件的Web界面......并且我尝试使用脚本而不是Web界面执行该操作......并且如果我执行uplaod与网络接口...和文件的内容类型是错误的,当我这样做与脚本 – VanDeath

回答

2

在它说documentation for poster.encode.MultipartParam

如果filetype设置,它被用作将Content-Type此参数。如果未设置,则默认为“text/plain;字符集= UTF8”

因此而不是指定你这样的参数:

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

指定它们是这样的:

params = [MultipartParam('restore', open("Config.cfg", "rb"), 
         filetype = 'application/octet-stream'), 
      ('upload', 'PC ==>; Unit')] 
与Python transfering文件时,[错误的内容类型的
+0

Thx非常多! = d – VanDeath