I have a file upload which works perfectly, however I want to write a test for it so I did the following....
def test_post_ok(self):
image = Image.new('RGB', (100, 100)
tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
image.save(tmp_file)
payload = {
"name": "Test",
"thumbnail_image": tmp_file
}
api = APIClient()
api.credentials(Authorization='Bearer ' + self.token)
response = api.post(url, payload, format='multipart')
However, the test gives the error...
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1024x768 at 0x108A5DCF8>
{'thumbnail_image': [u'The submitted file is empty.']}
I assume I'm not doing this correctly, if not why?
My earlier guess is wrong. You are using the Rest Framework with the multipart functionality (awesome!) so you can send the file as-is and the file will be encoded multipart.
The error here is the following:
tmp_file
tmp_file.read()
. Since the pointer is still at the end of the file,read()
will return 0 bytes, leaving you with an empty document.Solutions:
tmp_file.seek(0)
or reopen the file before callingpost()