我建立了<代码>no javascript 代码,其中使用html> 表格
和django view
上载文件。 它使用<代码>html5 输入要素选定文档。 在点击<代码>submit纽吨时,文档在无问题的情况下上载。 django 的观点可从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>
Now I want to use some javascript
to call the django
view .
I have coded ajax version of upload view
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")
令我感到困惑的是,<代码>>>>>>>>> 物体如何从<代码>javascript上通过。 code。
javascript Code
$(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;
}