看了网上很多代码,都没有说如何具体的使用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>
|