Many friends in the message area to ask about python upload files and characters to the server, now the editor for this to organize a solution for you.
Upload simple strings
def send_str_server(self): payload = {'key1': 'value1', 'key2': 'value2'} r = ("/post", data=payload)
Introduction: A payload is data in the form of key-value pairs, and the data on the server is displayed as
key1=value1&key2=value2
/post is the address of the uploading server
Uploading files
def send_image_server(self): data = {"k1" : "v1"} files = {"img" : open("", "rb")} r = ("/post", data, files=files)
Introduction: data is data in the form of key-value pairs, data carried by post requests
files in the img represents the php server on the image of the filter field, open in the first parameter for the address of the image, the second parameter represents the binary file write permission, /post is the address of the server
python post method upload file to php server
Looked at a lot of code on the Internet, did not say how to specifically use poster, tried for two days, finally succeeded!
File uploads via python calls to php.
Share this with everyone:
First you have to install poster via pip (easy_install does the same thing):
pip install poster
#!usr/bin/python # # -*- coding=utf-8 -*- from import multipart_encode import urllib2 import sys from urllib2 import Request, urlopen, URLError, HTTPError from import multipart_encode from import register_openers register_openers() f=open(“C:/Users/User/Pictures/Saved Pictures/”, "rb") #f=open([1], "rb") Use [1] callable argument Example Run python C:/Users/User/Pictures/Saved Pictures/ # can be passed as a parameter to the #"C:/Users/User/Pictures/Saved Pictures/" # headers contain the required Content-Type and Content-Length # datagen is a generator object that returns the encoded argument datagen, headers = multipart_encode({"myFile": f}) # Create request objects request = ("http://localhost/upload_image/upload_image.php", datagen, headers) try: response = (request) print () except URLError,e: print print ----- upload_image.php ---- <?php echo $_FILES['myFile']['name']; if (isset($_FILES['myFile'])) { $names = $_FILES["myFile"]['name']; $arr = explode('.', $names); $name = $arr[0]; //Photo name $date = date('Y-m-d H:i:s'); // Upload Date $fp= fopen($_FILES['myFile']['tmp_name'], 'rb'); $type = $_FILES['myFile']['type']; $filename = $_FILES['myFile']['name']; $tmpname = $_FILES['myFile']['tmp_name']; // upload the file to the upload folder in the server root directory if(move_uploaded_file($tmpname,$_SERVER['DOCUMENT_ROOT']."/upload/".$filename)){ echo "upload image succeed"; }else{ echo "upload image failed"; } } ?>
The above is a small pro-test about python upload and files and characters to the PHP server code implementation of the two ways, if you still have better content you can leave a message below to us, together with the exchange of ideas.