Ez0r
Ez0r

Reputation: 190

Python - simple requests file upload didn't work

i created a simple html upload file :

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

and a simple php upload file :

<?php
$target_dir = "";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
?> 

i tested everything works perfectly i want to submit a file upload with python using requests module so i created this :

import requests
url = 'http://localhost/upload/up.html'
files = [('images', ('1.jpg', open('1.jpg', 'rb'), 'image/jpg'))]
r = requests.post(url, files=files)
print r.text

it will return the html page code and the file uploading is failed , any solution ?

Upvotes: 0

Views: 90

Answers (1)

vikramls
vikramls

Reputation: 1822

I think the issue is the name passed to post. Use fileToUpload rather than images like this:

files = [('fileToUpload', ('1.jpg', open('1.jpg', 'rb'), 'image/jpg'))]
r = requests.post(url, files=files)

Upvotes: 2

Related Questions