1

I'm trying to test an image upload field with django 1.7, DRF 2.4.3 and Pillow 2.6.1.

File upload is working properly from the admin and when i test using curl

curl -X POST -S -H 'Accept: application/json' -F 'my_image=@hm.jpg;type=image/jpg' http://localhost:8000/api/randomresource/

When i ran a similar test in an APITestCase

temp_file = open('hm.jpg',"r")
response = self.client.post('randomresource', {"my_image":temp_file}, format='multipart')
self.assertEqual(response.status_code,status.HTTP_201_CREATED)

I get

{'my_image': [u'Upload a valid image. The file you uploaded was either not an image or a corrupted image.']}

Appreciate any help with this one. Thanks.

haki
  • 9,389
  • 15
  • 62
  • 110

1 Answers1

2

@mariodev answered this in the comments yesterday:

Have you tried the rb flag instead of r?

This is because otherwise you uploading the file with an encoding. For text files, and other non-binary files, this shouldn't be an issue, but for cases such as image files you need to open it as a binary file.

temp_file = open('hm.jpg',"rb")

When Django REST Framework checks that the image is valid using Pillow, it will raise an exception if the encoding is wrong. This is why you are getting the error, as Django REST Framework got a file upload, but can't verify that it is an image. The encoding was correct when using curl, because curl was uploading it as a binary file and was handling it all for you.

Community
  • 1
  • 1
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237