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 '[email protected];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.

1
  • 1
    Have you tried the rb flag instead of r? Commented Dec 7, 2014 at 18:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.