2

I have a python script that is supposed to upload a file to a php script.

Python

import requests

file={'file':('text.txt','hello')}

url='mywebsite.org/test.php


response = requests.post(url, files=file)
                              
print(response.text)

PHP

<?php
    var_dump($_FILES);
    var_dump($_POST);
?>

This is the response that I am getting to the python script:

array(0) {

}

array(0) {

}

However, when I try posting to http://httpbin.org/post,

I get

...

"files": {

"file": "hello"

},

...

Which seems to indicate that there is something wrong with my server. What might be the problem?

Community
  • 1
  • 1
Quizzical
  • 153
  • 4

1 Answers1

2

It seems there is problem in you python code - currently you do not send file since it is not open. Suppose your text.txt contains 1234. Posting it to http://httpbin.org/post like this:

import requests

file={'file':(open('text.txt','r').read())}

url='http://httpbin.org/post'

response = requests.post(url, files=file)

print(response.text)

We get follow response:

...
"files": {
    "file": "1234"
  },
...

If you want to add some extra parameters, you can do it like this:

values = {'message': 'hello'}
response = requests.post(url, files=file, data=values)
NorthCat
  • 9,643
  • 16
  • 47
  • 50
  • 1
    Thank you for your reply, but having tried this solution, I have found it still does not work. The requests library offers the functionality of posting text as a file, e.g. when posting file={'file':('text.txt','hello')}, this sends a file named 'text.txt' that contains the string 'hello'. This is not the problem, as I can see that http://httpbin.org/post replies that I have in fact posted the file there. – Quizzical Jun 04 '14 at 14:57
  • You're right, I did not know about this feature of `requests` library. Both methods work on my server. Ok, what about these solutions?: http://stackoverflow.com/questions/3586919/why-would-files-be-empty-when-uploading-files-to-php – NorthCat Jun 05 '14 at 08:16