Categories
Development PHP Python

How to send multipart/data to PHP using Python requests

I’ve been trying to send an image to another server for a very long time, but for some reason it doesn’t want to accept files through requests.
In the response, I get {“error”: “No panorama provided. Files = []”, “files”: []}.
How do I build a request correctly?
Correct code JS: https://gitlab.com/nickw1/opentrailview/blob/master/js/uploader.js

Python POST code:
upload_url = 'https://opentrailview.org/oauth/api/panorama/upload'  
headers = {
    'Authorization': 'Bearer ' + token
}

with open('photos/multi-photo/sor.jpg', 'rb') as img_file:
    img = img_file.read()

files = {'file': ('sor.jpg', img, 'image/jpeg', {'Expires': '0'})}

r = requests.post(upload_url, files=files, headers=headers)
print(r.text)

On the other side I have this code

PHP Code:
 private function uploadPano(Request $req, Response $res, array $args) {
    $files = $req->getUploadedFiles();
    $error = $warning = null;
    $errorCode = 400;
    if(!$this->authorisedToUpload()) {
        $errorCode = 401;
        $error = "You must be authenticated to upload panos.";
    } elseif(empty($files['file'])){
        $error = "No panorama provided. files=".json_encode($files);
    } else {
        $pano= $files['file'];
        if($pano->getError() != UPLOAD_ERR_OK) {
            $error = "No file uploaded. Your file probably exceeds the max file size of ". MAX_FILE_SIZE. "MB. Error code=". $pano->getError();
        } else {
            $size = $pano->getSize();    
            if($size > MAX_FILE_SIZE * 1048576) {
                $error = "Exceeded file size of ".MAX_FILE_SIZE." MB";
            } else {
                $tmpName=$pano->file;
                $imageData = getimagesize($tmpName);
                if($imageData===false || $imageData[2]!=IMAGETYPE_JPEG) {
                    $error = "Not a JPEG image!";
                }

Leave a Reply

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