我有一个从输入字段中选择的图像文件,并通过django中的表单发布。
表单数据和我要发布到其他服务器的图像
问题似乎是,请求中的文件数据是InMemoryUploadedFile类型,需要与其他发布的数据(json格式)一起转换。
基本上我的代码是:
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)
无论我尝试什么......文件都不会上传到服务器。
记录responese ...项目已创建...但image = null
任何人都建议我在这里俯瞰......
2013年周二编辑 - 6 - 4
我将此记录放在最后:'if files'部分 logger.debug('DEBUG:datagen:%s'%datagen) logger.debug('DEBUG:headers:%s'%headers)
我在那边得到了这个:
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'}
更多信息: 我是从jquery输入表单发送它
html中的表单如下:
<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>
答案 0 :(得分:0)
这很有帮助:Post request with multipart/form-data in appengine python not working
似乎multipart_encode无法直接获取内存文件...
所以我将代码更改为:
添加了导入:
from poster.encode import MultipartParam
files["image"]= MultipartParam("image", filename=memfile.name, filetype=memfile.content_type, fileobj=memfile.file)
这很有效!!!