3

I've written a simple script to expand my skills with python - however I've noticed something very strange when using BytesIO.

Here's my working script:

import requests

url = "http://MY.FAKE.IP.ADDR/Uploader.php"
file = open("test.jpg","rb")
action = {"file" : file, "name" : "test.jpg"}
requests.post(url, files=action) 

However, when I try to do the same thing with an image in the memory (for example, a screenshot), the webserver gets a blank filename?? Here's my code for this:

import requests
from PIL import ImageGrab
from io import BytesIO

url = "http://MY.FAKE.IP.ADDR/phUploader.php"

file_name = "test.jpg"

im = ImageGrab.grab()
output = BytesIO()
im.save(output, "JPEG")

file = output.getvalue()

action ={"file":file,"name":file_name}

requests.post(url,files=action)

What the file looks like on the webserver:

enter image description here

However the file once renamed - does contain my image as intended. I can't find anything on this, it's really confusing why this script doesn't work.

Piero Bird
  • 119
  • 1
  • 10

1 Answers1

3

You're constructing your requests files argument wrong, check the official documentation on how to construct it.

In your case: action = {"file": (file_name, file)} should do the trick.

zwer
  • 24,943
  • 3
  • 48
  • 66
  • Thank you, I'll read up on it. I learned from a source I suppose that taught me wrong. – Piero Bird Jun 09 '17 at 17:47
  • @PieroBird - always check the official documentation before you resort to external sources, including SO - the assumption being that the developers of the module should know the best how to use it. – zwer Jun 09 '17 at 17:50
  • Understood, I'll be sure to do that in the future. – Piero Bird Jun 09 '17 at 17:52