了Apache,PHP,Python的上傳文件到PHP服務器使用Python客戶端和接收
這個問題已經被問在多個場合這個網站上,但是被很新的Python和PHP,這是我很難找出一個正確的方法來做到這一點。
目前 我的客戶端的部分看起來像(拉鍊文件,並將其發送)
1 #!/usr/bin/python
2
3 import os
4 import zipfile
5 import sys
6 import hashlib
7 from poster.encode import multipart_encode
8 from poster.streaminghttp import register_openers
9 import urllib2
10
11 def zip(src, dst):
12 zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
13 abs_src = os.path.abspath(src)
14 for dirname, subdirs, files in os.walk(src):
15 for filename in files:
16 absname = os.path.abspath(os.path.join(dirname, filename))
17 arcname = absname[len(abs_src) + 1:]
18 print 'zipping %s as %s' % (os.path.join(dirname, filename), arcname)
19 zf.write(absname, arcname)
20 zf.close()
21
22 # zip the file using source to the destination.. can do some error checks here
23 zip(sys.argv[1], sys.argv[2])
24
25 # create md5
26 md5 = hashlib.md5(open(sys.argv[2]+".zip", 'rb').read()).hexdigest()
27
28 # Register the streaming http handlers with urllib2
29 register_openers()
30
31 filename=sys.argv[2]+".zip"
32
33 # headers contains the necessary Content-Type and Content-Length
34 # datagen is a generator object that yields the encoded parameters
35 datagen, headers = multipart_encode({
36 'type' : 'zip',
37 'name' : "hello.zip",
38 'file' : open(filename)
39 })
40
41 # make a call
42 request = urllib2.Request("http://localhost/upload.php", datagen, headers)
43
44
45 # Actually do the request, and get the response
46 print urllib2.urlopen(request).read()
服務器側面看上去就像是
1 <?php
2 if ($_FILES["file"]["error"] > 0) {
3 echo "Error: " . $_FILES["file"]["error"] . "<br />";
4 } else {
5 echo "Upload: " . $_FILES["file"]["name"] . "<br />";
6 echo "Type: " . $_FILES["file"]["type"] . "<br />";
7 echo "Size: " . ($_FILES["file"]["size"]/1024) . " Kb<br />";
8 echo "Stored in: " . $_FILES["file"]["tmp_name"];
9 }
15
16
17 ?>
當我跑我的Python文件,我得到這個輸出
上傳:
類型:
大小:0 KB
在存儲:
這種情況特別適用於較大的文件。問題的
第二部分,當我發送的小文件,我看到這個
Upload: upload.php<br />Type: application/x-httpd-php<br />Size: 0.4775390625 Kb<br />Stored in: /private/var/tmp/phpHapPaO
Beautiful-iMac:~ agauravdeep$ open /private/var/tmp/
Beautiful-iMac:~ agauravdeep$ cd /private/var/tmp/phpHapPaO
-bash: cd: /private/var/tmp/phpHapPaO: No such file or directory
Beautiful-iMac:~ agauravdeep$ vi /private/var/tmp/phpHapPaO
You have new mail in /var/mail/agauravdeep
但什麼也沒有。正如在下面的評論中提到,我試圖更新php.ini.default但我沒有得到任何改變與更新的phpinfo即使重啓
這些工作完全符合我的要求(加上python腳本導入)。我得到的輸出如下:'Upload:.zshrc
類型:text/plain
大小:0.9697265625 Kb
存儲在:/ tmp/phplocfny' – kalhartt
你是對的..我發送了一個小文件,它工作,但我發送一個巨大的文件,並不起作用.. –
你發送什麼大小的文件?它爲我工作〜900Mb文件。 – kalhartt