python上传文件|怎么用http上传一个文件到服务器 python

python上传文件|怎么用http上传一个文件到服务器 python的第1张示图

① 如何在 Python 中模拟 post 表单来上传文件

最近有个将文件上传到内部web服务器上的任务,于是参考了网上部分源码用python写了这个小程序,代码如下:

[python]view plain

#coding:utf-8

'''''

Createdon2015.3.19

@author:damofy

'''

importos

importtime

importsys

importurllib2

'''''

filename待上传的文件

fieldname表单域中的name属性

'''

defCreateBody(filename,fieldname,strBoundary):

bRet=False

sData=[]

sData.append('–%s'%strBoundary)

#'Content-Disposition:form-data;name="uploadfile";filename="XX-Net-1.3.6.zip"'

sData.append('Content-Disposition:form-data;name="%s";'%fieldname+'filename="%s"'%os.path.basename(filename))

sData.append('Content-Type:%s'%'application/octet-stream')

try:

pFile=open(filename,'rb')

sData.append(pFile.read())

sData.append('–%s–'%strBoundary)

bRet=True

finally:

pFile.close()

returnbRet,sData

defuploadfile(http_url,filename,fieldname):

ifos.path.exists(filename):

filesize=os.path.getsize(filename)

print('file:'+filename+'is%dbytes!'%filesize)

else:

print('file:'+filename+'isn'texists!')

returnFalse

strBoundary='—————————%s'%hex(int(time.time()*1000))

bRet,sBodyData=CreateBody(filename,fieldname,strBoundary)

ifTrue==bRet:

http_body=''.join(sBodyData)

stReq=urllib2.Request(http_url,http_body)

stReq.add_header('User-Agent','Mozilla/5.0')

stReq.add_header('Content-Length:','%d'%filesize)

stReq.add_header('Content-Type','multipart/form-data;boundary=%s'%strBoundary)

resp=urllib2.urlopen(stReq,timeout=5)

#getresponse

msg=resp.read()

print("Responsecontent:"+msg)

else:

print("CreateBodyfailed!")

returnbRet

if__name__=='__main__':

iflen(sys.argv)>2:

http_url=sys.argv[1]

filename=sys.argv[2]

else:

print('pythonupload.pyhttp://10.20.131.23/upload./test.dat')

sys.exit()

#参数3"uploadfile"是post表单中的name属性,需要与服务端保持一致

uploadfile(http_url,filename,'uploadfile')

② python selenium怎么自动上传文件

给你个例子:

ifnotimg_path:img_path=os.path.abspath("../res/cvd_test.jpg")else:img_path=path.abspath(img_path)#up_img_input=WebDriverWait(self.driver,10).until(EC.presence_of_element_located((By.ID,"updli_file")))up_img_input.send_keys(img_path)send_img_btn=WebDriverWait(self.driver,10).until(EC.element_to_be_clickable((By.ID,"send-pic-img")))#time.sleep(self.send_interval)send_img_btn.click()

上面实现的工作就是,找到上传组件的那个input元素,然后把你要上传的文件的路径发送给ta

③ python文件转字节流上传

图片,视频都是二进制的,你读取的时候写 rb ,然后你在请求的时候记得把视频转成.content

像这样load_src = requests.get("http://"+srcs[i], headers=headers).content

④ 怎么用http上传一个文件到服务器 python

首先,标准HTTP协议对上传文件等表单的定义在这里:wwwietforg/rfc/rfc1867txt 大概数据包格式如下:单文件:Content-type: multipart/form-data, boundary=AaB03x–AaB03xcontent-disposition: form-data; name="field1"Joe Blow–AaB03xcontent-disposition: form-data; name="pics"; filename="file1.txt"Content-Type: text/plain… contents of file1.txt …–AaB03x–多文件:Content-type: multipart/form-data, boundary=AaB03x–AaB03xcontent-disposition: form-data; name="field1"Joe Blow–AaB03xcontent-disposition: form-data; name="pics"Content-type: multipart/mixed, boundary=BbC04y–BbC04yContent-disposition: attachment; filename="file1.txt"其次,python上传文件的几种方法:1 自己封装HTTP的POST数据包:http//stackoverflowcom/questions/680305/using-multipartposthandler-to-post-form-data-with-pythonimport httplibimport mimetypesdef post_multipart(host, selector, fields, files): content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTP(host) h.putrequest('POST', selector) h.putheader('content-type', content_type) h.putheader('content-length', str(len(body))) h.endheaders() h.send(body) errcode, errmsg, headers = h.getreply() return h.file.read() def encode_multipart_formdata(fields, files): LIMIT = '———-lImIt_of_THE_fIle_eW_$' CRLF = '\r\n' L = [] for (key, value) in fields: L.append('–' + LIMIT) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files:

⑤ 如何把python代码上传到服务器上

使用pip或easy_install可以管理和安装python的package包,实际上它们都是从pypi服务器中搜索和下载package的。目前在服务器上,有超过三万多个package,同时还允许我们将自己的代码也上传发布到服务器上。这样,世界上的所有人都能使用pip或easy_install来下载使用我们的代码了。具体步骤如下:首先创建项目文件和setup文件。目录文件结构如下:project/simpletest/__init__.pytest.pysetup.py假设项目文件只有一个simpletest包,里面有一个test.py文件。创建的setup.py文件格式大致如下,其中,install_requires字段可以列出依赖的包信息,用户使用pip或easy_install安装时会自动下载依赖的包。详细的格式参考文档。from setuptools import setup, find_packagessetup(name = 'simpletest',version = '0.0.1',keywords = ('simple', 'test'),description = 'just a simple test',license = 'MIT License',install_requires = ['simplejson>=1.1'],author = 'yjx',author_email = '[email protected]',packages = find_packages(),platforms = 'any',)然后将代码打包。打包只需要执行pythonsetup.py xxx命令即可,其中xxx是打包格式的选项,如下:# 以下所有生成文件将在当前路径下 dist 目录中python setup.py bdist_egg # 生成easy_install支持的格式 python setup.py sdist # 生成pip支持的格式,下文以此为例发布到pypi。发布到pypi首先需要注册一个账号,然后进行如下两步:注册package。输入python setup.py register。上传文件。输入python setup.py sdist upload。安装测试上传成功后,就可以使用pip来下载安装了。另外,pypi还有一个测试服务器,可以在这个测试服务器上做测试,测试的时候需要给命令指定额外的"-r"或"-i"选项,如pythonsetup.py register -r "",pythonsetup.py sdist upload -r "",pipinstall -i "" simpletest。发布到测试服务器的时候,建议在linux或cygwin中发布,如果是在windows中,参考文档,需要生成.pypirc文件

⑥ python能直接通过url上传文件吗

可以这样写:专urls = sel.xpath('//li[@属class="next_article"]/a/@href').extract() for url in urls: url = "http://blog.csdn.net" + url yield Request(url, callback=self.parse)

⑦ 如何用python实现上传本地指定文件夹下文件(文件名称均为数字,以数字顺序上传)到远端指定路径

这要看你的本地与远端允许哪些通信方式(协议)

⑧ Python的文件上传

Python中使用GET方法实现上传文件,下面就是用Get上传文件的例子,client用来发Get请求,server用来收请求。

请求端代码:

importrequests#需要安装requestswithopen('test.txt','rb')asf:requests.get('http://服务器IP地址:端口',data=f)

服务端代码:

varhttp=require('http');varfs=require('fs');varserver=http.createServer(function(req,res){//console.log(req);varrecData="";req.on('data',function(data){recData+=data;})req.on('end',function(data){recData+=data;fs.writeFile('recData.txt',recData,function(err){console.log('filereceived');})})res.end('hello');})server.listen(端口);

⑨ 如何使用python在局域网上传送文件

浏览器输入框输入文件所在主机 IP 。

⑩ python、FileReference、上传文件

数据微化处理传送

未经允许不得转载:山九号 » python上传文件|怎么用http上传一个文件到服务器 python

赞 (0)