Easy Code Share > Python > 4 Practices for Python File Upload to PHP Server

4 Practices for Python File Upload to PHP Server


Python File Upload will be introduced by 4 methods. All of them have no relationship with browser clients. Instead, scripts runs to upload using command lines.

We don’t mention about HTTP file upload service in Python, but the server site just use a PHP solution that has been discussed in our previous articles Single File Upload Server and Multiple File Upload Server.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

New Post: Python HTTP Server Accept File Upload in Two Ways

Estimated reading time: 8 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.

Specially about Python, you can refer to the following.

  • Prepare Python environment for Windows by clicking Python Downloads, or search a Python setup pack for Linux.
  • The pack of Windows version also contains pip install for you to obtain more Python libraries in the future.
 DOWNLOAD SOURCE

 

SECTION 1
Python Single File Upload

As well as our previous article about PHP Single File Upload, let us discuss Python methods for file upload with its famous library requests.

 

Method 1A – Python Upload (File)

Python File Upload Without Data

There are many libraries Python uses to implement functions or skills in various fields. Usually for the topic of File Upload, developers write codes with an elegant and simple HTTP library by installing PyPI requests.

Above is an example Single File Upload looks like. requests.post(url, files=file) just contains parameters url and files=file. For the second parameter, file is of data type DICT with a file handle in it. Where DICT is an important data type in Python.

upload-1A.py
 # upload file by python
 import requests;
 def hconn_send() :
     url = 'http://localhost/wpp/exams/a0012/server/single-upload.php'
     file = {'myfile': open('images/in_transit.png','rb')}
     r = requests.post(url, files=file)
     if r.status_code != 200:
         print('sendErr: '+r.url)
     else :
         print(r.text)
 # main
 hconn_send()

If you have already install Python and related libraries in your environment, test programs by executing the following command line.

C:\>python upload-1A.py
filename : in_transit.png

 

Method 1B – Python Upload (File & Data)

Python File Upload With Data

Apart from simply file upload, you had better send one file along with data at a time in some situations. Using a DICT data type such as item={} can carry text messages, and then the text content will represent a parameter data=item in requests.post() for upload.

upload-1B.py
 # upload file along with data by python
 import requests;
 def hconn_send() :
     url = 'http://localhost/wpp/exams/a0012/server/single-upload.php'
     item = {"method": "method 2", "msg": "upload file along with data by python"}
     file = {'myfile': open('images/in_transit.png','rb')}
     r = requests.post(url, data=item, files=file)
     if r.status_code != 200:
         print('sendErr: '+r.url)
     else :
         print(r.text)
 # main
 hconn_send()

Command lines illustrate the result.

C:\>python upload-1B.py
Array
(
    [method] => method 2
    [msg] => upload file along with data by python
)
filename : in_transit.png

 

SECTION 2
Python Multiple File Upload

Python methods are straight forword. For multiple file upload, the library requests just enlarges its DICT parameter files to hold more than one file handles. However, the way to index in DICT should be noticed.

 

Method 2A – Python Multiple Upload (File)

Python Multiple File Upload Without Data

Let us focus on the topic of multiple file upload simultaneously. Extend from the previous section, the only thing to do is replace file with filelist. And all keys in filelist should form an integer-indexed array looks like myfile[].

upload-2A.py
 # upload multiple files by python
 import requests;
 def hconn_send() :
     url = 'http://localhost/wpp/exams/a0012/server/multiple-upload.php'
     namelist = ['images/in_transit.png', 'images/home.png', 'images/customer_support.png']
     filelist = dict()
     for i in range(0, len(namelist)) :
         filelist['myfile['+ str(i) +']'] = open(namelist[i],'rb')
     r = requests.post(url, files=filelist)
     if r.status_code != 200:
         print('sendErr: '+r.url)
     else :
         print(r.text)
 # main
 hconn_send()

A segment of codes from the above is helpful for you to learn how to put multiple file handles into filelist. In addition, the DICT data type filelist should be indexed by integer, thus the server site can identify each file handle with ease.

C:\>python upload-2A.py
success:
Array
(
    [0] => in_transit.png
    [1] => home.png
    [2] => customer_support.png
)

 

Method 2B – Python Multiple Upload (File & Data)

Python Multiple File Upload With Data

At last, a Python example shows library requests can upload multiple file upload along with JSON-like messages at a time. The details are similiar to that in previous sections.

upload-2B.py
 # upload multiple files along with data by python
 import requests;
 def hconn_send() :
     url = 'http://localhost/wpp/exams/a0012/server/multiple-upload.php'
     json_data = {"method": "method 4", "msg": "upload multiple files along with data by python"}
     namelist = ['images/in_transit.png', 'images/home.png', 'images/customer_support.png']
     filelist = dict()
     for i in range(0, len(namelist)) :
         filelist['myfile['+ str(i) +']'] = open(namelist[i],'rb')
     r = requests.post(url, data=json_data, files=filelist)
     if r.status_code != 200:
         print('sendErr: '+r.url)
     else :
         print(r.text)
 # main
 hconn_send()

Here is the result looks like,

C:\>python upload-2B.py
Array
(
    [method] => method 4
    [msg] => upload multiple files along with data by python
)
success:
Array
(
    [0] => in_transit.png
    [1] => home.png
    [2] => customer_support.png
)

 

SECTION 3
PHP File Upload Server

At server site, we choose PHP, instead of Python, as the language to write for a single or multiple file upload servers. The reason is that PHP gets better relationship with the popular HTTP service Apache than Python from the view of integrity.

If ignoring integrity with database or other services, there are still some Python libraries that can build a stand-alone HTTP service to accept file transfer.

 

Single File Upload Service

Move Uploaded File From Temporary Area

PHP always stores incoming files in a temporary area first, and then pushes related information to the file upload server using a PHP super global variable $_FILES[]. Subsequently, the server will call move_uploaded_file() to move them to target area.

[myfile] => Array
(
    [name] => in_transit.png
    [type] => application/octet-stream
    [tmp_name] => C:\xampp\tmp\phpBD73.tmp
    [error] => 0
    [size] => 8861
)
single-upload.php
<?php
/* upload one file */
$upload_dir = 'uploads';
$name = basename($_FILES["myfile"]["name"]);
$target_file = "$upload_dir/$name";
if ($_FILES["myfile"]["size"] > 10000) { // limit size of 10KB
    echo 'error: your file is too large.';
    exit();
}
if (!move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file))
    echo 'error: '.$_FILES["myfile"]["error"].' see /var/log/apache2/error.log for permission reason';
else {
    if (isset($_POST['data'])) print_r($_POST['data']);
    echo "\n filename : {$name}";
}
?>

Remember to grant write privileges on the destination folder to Apache user in Linux. The action will allow HTTP service to create new files in this folder. Our another article about Single File Upload Server writes more about this topic.

 

Multiple File Upload Service

Move Uploaded File From Temporary Area

Let us see what information a PHP server site will get about multiple file upload.

[myfile] => Array
(
    [name] => Array
        (
            [0] => in_transit.png
            [1] => home.png
            [2] => customer_support.png
        )
    [type] => Array
        (
            [0] => application/octet-stream
            [1] => application/octet-stream
            [2] => application/octet-stream
        )
    [tmp_name] => Array
        (
            [0] => C:\xampp\tmp\php106C.tmp
            [1] => C:\xampp\tmp\php107C.tmp
            [2] => C:\xampp\tmp\php107D.tmp
        )
    [error] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
        )
    [size] => Array
        (
            [0] => 8861
            [1] => 5871
            [2] => 4017
        )
)

Unlike single upload, multiple upload indexs files by interger. For each file, do check if error code is UPLOAD_ERR_OK, and then move temporary files to your target place. You can read more about this topic in Multiple File Upload Server.

multiple-upload.php
<?php
/* upload multiple files in one request */
$upload_dir = 'uploads/';
$namelist = array();
foreach ($_FILES["myfile"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $name = basename($_FILES["myfile"]["name"][$key]);
        $target_file = "$upload_dir/$name";
        if ($_FILES["myfile"]["size"][$key] > 10000) { // limit size of 10KB
            echo "error: {$name} is too large. \n";
            continue;
        }
        if (!move_uploaded_file($_FILES["myfile"]["tmp_name"][$key], $target_file))
            echo 'error:'.$_FILES["myfile"]["error"][$key].' see /var/log/apache2/error.log for permission reason';
        else
            $namelist[] = $name;
    }
}
if (isset($_POST['data'])) print_r($_POST['data']);
echo "\n success: \n";
print_r($namelist);
?>

 

FINAL
Conclusion

If interested in HTTP file upload service in Python solution, you can refer to Flask Uploading Files. Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Suggested Reading

Leave a Comment