Python Beginner’s Guide to Post Binary Data to Server – Python Tutorial

By | August 11, 2019

In  tutorial ‘A Simple Guide to Python 3 Urllib Post Data to Server‘, we know how to post string data to server in python 3. However, how to post binary data, such as image, pdf files to server? In this tutorial, we will show you how to post a binary data to server with an example.

Open an image to get binary data

file = "1.png"
image_data = ''
with open(file, 'rb') as f:
    image_data = f.read()

Build a data to post

def buildData(file_name, image_data):
    data = {'file_name':file_name, 'image_data': image_data}
    return data 
data = buildData(file, image_data)

Create a server php script to save binary data

url = 'http://127.0.0.1/save-image.php'

This page is a php script, the content of it is:

<?php
$file_name = $_POST['file_name'];
$image_data = $_POST['image_data'];

file_put_contents($file_name,$image_data);
?>

Post data to server

content = netutil.sendData(url, data)
print(content)

The netutil package is defined refer to tutorial:

A Simple Guide to Python 3 Urllib Post Data to Server – Python Tutorial

From this tutorial, we can find:

Post a binary to server is similar to post a string data to server.

Leave a Reply

Your email address will not be published. Required fields are marked *