我尝试使用 ajax 提交此表单,以便 django 视图可以从 request.FILES 中提取所选文件并写入服务器上的目录
<form enctype="multipart/form-data" method="post" id="fileupoadform">{% csrf_token %}
<p>
<label>Select a file
<input type="file" name="fselect" id="fselect"> </input>
</label>
</p>
<input type="submit" value="upload">
</form>
观点是
def ajax_upload(request):
print 'ajax_upload()'
print 'request=',request
to_return = {}
store_message="failure"
if (request.is_ajax()) and (request.method == 'POST'):
print 'is ajax and post'
print 'request.FILES=',request.FILES
if request.FILES.has_key('fselect'):
print "request has key='fselect'"
file = request.FILES['fselect']
with open(settings.UPLOADPATH'%s' % file.name, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
store_message="success"
to_return['store_message']= store_message
print 'to_return=',to_return
to_return['store_message']= store_message
serialized = simplejson.dumps(to_return)
print 'serialized=',serialized
if store_message == "success":
print 'suceessfully returning'
return HttpResponse(serialized, mimetype="application/json")
else:
print 'failed!! returning'
return HttpResponseServerError(serialized, mimetype="application/json")
我使用 jquery 使 ajax 提交
$(document).ready(function(){
$('#fileupoadform').submit(function(e){
submitUploadForm(e);
});
});
function submitUploadForm(e){
console.log('clicked submit');
e.preventDefault();
var file = $('#fselect').get(0).files[0];
console.log('filename='+file.name)
var data = { name:file.name };
var args = { type:"POST", url:"upload/", data:data, complete:doneAjaxUpload };
$.ajax(args);
}
当我尝试这个时,我得到了这个控制台输出
ajax_store_uploaded_file()
request= <WSGIRequest
GET:<QueryDict: {}>,
POST:<QueryDict: {u'name': [u'myfile.srt']}>,
COOKIES:{'csrftoken': 'ca367878345fa9e59adf79hg047a1dvb'},
...
is ajax and post
request.FILES= <MultiValueDict: {}>
to_return= {'store_message': 'failure'}
serialized= {"store_message": "failure"}
failed!! returning
[01/Jun/2012 11:27:26] "POST /myapp/upload/ HTTP/1.1" 500 28
我感觉到我在 django 视图中做错了什么。是我无法从 .In 获取上传的文件吗?我request.FILES
能够non ajax version
使用django view
request.FILES 从 request.FILES 获取文件request.FILES['fselect']
有人可以帮我解决这个问题吗?