【问题标题】:How to Change Content-Type Python如何更改内容类型 Python
【发布时间】:2012-09-22 07:41:06
【问题描述】:

我想将文件上传到远程设备。 如果我查找与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()

【问题讨论】:

  • 这完全不清楚。什么是服务器,什么是客户端,你在哪里设置内容类型/配置?
  • 服务器是 10.128.115.214 saveRestore.htm.cgi 是一个用于上传和恢复文件的 Web 界面...我尝试使用脚本而不是通过 Web 界面来实现...如果我使用 web 界面进行上传,则会出现 1 个 Wireshark ......并且当我使用脚本执行此操作时文件的 Content-Type 是错误的

标签: python post content-type


【解决方案1】:

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')]

【讨论】:

    猜你喜欢
    • 2012-09-22
    • 2018-08-30
    • 2018-05-20
    • 2010-10-29
    • 1970-01-01
    • 2016-12-07
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多