python 通过post方式上传文件到php服务器

看了网上很多代码,都没有说如何具体的使用poster,试了两天,终于成功了

通过python调用php实现了文件上传
与大家分享一下:
    首先要通过pip安装poster(easy_install 也是一样的):
1
pip  install  poster

 

image.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!usr/bin/python
# image.py
# -*- coding=utf-8 -*-
from  poster.encode  import  multipart_encode
import  urllib2
import  sys
from  urllib2  import  Request, urlopen, URLError, HTTPError
from  poster.encode  import  multipart_encode
from  poster.streaminghttp  import  register_openers
  
register_openers()
f = open (“C: / Users / User / Pictures / Saved Pictures / test1.jpg”,  "rb" )
#f=open(sys.argv[1], "rb")   使用sys.argv[1]可调用参数 例如 运行 python image.py  C:/Users/User/Pictures/Saved Pictures/test1.jpg
#可将test1.jpg作为参数传入image.py
#"C:/Users/User/Pictures/Saved Pictures/vedio5.jpg"
# headers 包含必须的 Content-Type 和 Content-Length
# datagen 是一个生成器对象,返回编码过后的参数
datagen, headers  =  multipart_encode({ "myFile" : f})
# 创建请求对象
request  =  urllib2.Request( "http://localhost/upload_image/upload_image.php" , datagen, headers)
try :
     response  =  urllib2.urlopen(request)
     print  response.read()
     
except  URLError,e:
     print  e.reason
     print  e.code

 

upload_image.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
     echo  $_FILES [ 'myFile' ][ 'name' ];
     if  (isset( $_FILES [ 'myFile' ]))
     {
         $names  $_FILES [ "myFile" ][ 'name' ];
         $arr    explode ( '.' $names );
         $name   $arr [0];  //图片名称
         $date   date ( 'Y-m-d H:i:s' );  //上传日期
         $fp     fopen ( $_FILES [ 'myFile' ][ 'tmp_name' ],  'rb' );
         $type   $_FILES [ 'myFile' ][ 'type' ];
         $filename  $_FILES [ 'myFile' ][ 'name' ];
         $tmpname  $_FILES [ 'myFile' ][ 'tmp_name' ];
         //将文件传到服务器根目录的 upload 文件夹中
         if (move_uploaded_file( $tmpname , $_SERVER [ 'DOCUMENT_ROOT' ]. "/upload/" . $filename )){
             echo  "upload image succeed" ;
         } else {
             echo  "upload image failed" ;
         }
     }
?><br><br><br>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值