I have an image file which is selected from an input field and posted via a form in django.
The form data and the image I want to post to another server .
The problem seems to be, the file data in the request is an InMemoryUploadedFile type, which need to be transformed together with other posted data (json format).
basically my code is:
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
def some_view(request):
files=None
if request.FILES:
key = 'expected_image_name' #something else here, but not relevant
if key in request.FILES:
memfile = request.FILES.get(key, None)
if memfile:
files={}
# note this works: but does not upload the file:
# files["image"]= memfile.read()
# So trying a lot of other things, like:
files["image"]= ContentFile(memfile.read(), name=memfile.name).read()
# I also retrieve some data from request.Post... but for simplycity lets say it is:
post_values = {"some_other_field": "whatever"}
register_openers()
url="My post url"
# for simplycity I leave out the authentication, the problem is not in there
if files:
multi_data=post_values
multi_data.update(files)
datagen, headers = multipart_encode(multi_data)
request = urllib2.Request(url, datagen, headers)
response = urllib2.urlopen(request)
else:
request = urllib2.Request(url)
response = urllib2.urlopen(request,data)
Whatever I try... the file does not get uploaded to the server.
logging the responese... the item is created... but the image = null
anybody a suggestion of what I Am overlooking here....
EDIT Tuesday 2013 - 6 - 4
I placed this logging in the last: 'if files' part logger.debug('DEBUG: datagen: %s' % datagen) logger.debug('DEBUG: headers: %s' % headers)
I got this over there:
DEBUG get_response: datagen: <poster.encode.multipart_yielder instance at 0x7fdb7cca4200>
DEBUG get_response: headers: {'Content-Length': '30349', 'Content-Type': 'multipart/form-data; boundary=baa9e321554a49c6b626c68860a90aaf'}
And more info: I Am sending it from jquery input form
the form in html looks like:
<form data-ajax="false" id="form_5" method="post" enctype="multipart/form-data" action="My url to the view above">
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='z47GsVwsBOzu3HrUMIZaI4hoyV2ljLVa' /></div>
<!-- and some other fields in input fields -->
<input type="file" name="expected_image_name" data-role="button" id="expected_iamge_name" value="Select photo"/>
<input type="submit" value="Submit">
</form>
This was helpfull: Post request with multipart/form-data in appengine python not working
It seems the multipart_encode cannot take a memory file directly...
so I changed my code in to:
added an import:
from poster.encode import MultipartParam
files["image"]= MultipartParam("image", filename=memfile.name, filetype=memfile.content_type, fileobj=memfile.file)
And this works!!!