I created a no javascript
code which uses an html form
and django view
to upload a file .It uses an html5 input
element for selecting the file.On clicking the submit
button,the file gets uploaded without any problem.The django view can get the file from 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)
the html form is
<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")
I am confused about how the file
object can be passed from javascript
code to django view.
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;
}