我创建了一个使用和上传文件的no javascript
代码。它使用一个元素来选择文件。单击按钮后,文件上传没有任何问题。django 视图可以从中获取文件html form
django view
html5 input
submit
request.FILES
def upload_file(request,template_name):
to_return = {}
store_message="failure"
if request.method == 'POST':
if request.FILES.has_key('fselect'):
file = request.FILES['fselect']
with open('/uploadpath/%s' % file.name, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
store_message="success"
to_return['store_message']= store_message
if store_message == "failure":
return redirect('home')
reqctx = RequestContext(request,to_return)
return return render_to_response(template_name,reqctx)
html表单是
<form enctype="multipart/form-data" method="post" action="{% url uploaded %}"> {% csrf_token %}
<input type="file" name="fselect" id="fselect"> </input>
<input type="submit" id="uploadbtn" value="upload">
</form>
现在我想用一些javascript
来调用django
视图。我已经编写了上传视图的 ajax 版本
def ajax_upload_file(request):
to_return = {}
store_message="failure"
if request.method == 'POST':
if request.FILES.has_key('fselect'):
file = request.FILES['fselect']
with open('/uploadpath/%s' % file.name, 'wb+') as dest:
for chunk in file.chunks():
dest.write(chunk)
store_message="success"
to_return['store_message']= store_message
serialized = simplejson.dumps(to_return)
if store_message == "failure":
return HttpResponseServerError(serialized, mimetype="application/json")
else:
return HttpResponse(serialized, mimetype="application/json")
我对如何将file
对象从javascript
代码传递到 django 视图感到困惑。
javascript代码
$(document).ready(function(){
$('#fselect').change(function(){uploadFile()});
}
function uploadSubTitleFile(){
//check if it is a subtitle file?
var file=document.getElementById('fselect').files[0];
var data = { };//how to pass the data
var args = { type:"POST", url:"ajax_upload/", data:data, complete:done };
return;
}