jquery - Django: How to upload a file using ajax -
i using django 1.5, python 2.7 , jquery 1.9. have form has precisely 2 fields i.e. title , document. when press submit want users chosen document present in request.files shown in view.
when submit regular form (without ajax), works fine, ajax not file field in request. suggestions on how upload file using ajax.
html:
<form enctype="multipart/form-data" action="{% url 'upload_document' %}" method="post" id="uploadform"> {% csrf_token %} <ul> <li> <div>title</div> <input id="title" type="text" maxlength="200"/> <div class="error"></div> </li> <li> <div>upload file</div> <input id="document" type="file" size="15" /> <div class="error"></div> </li> </ul> <input type="submit" value="submit"/></p> </form>
forms.py:
class uploadform( forms.form ): document = forms.filefield() title = forms.charfield(max_length = 200) def clean(self): cleaned_data = super(uploadform, self).clean() return cleaned_data def save(self, *args, **kwargs): title = self.cleaned_data['title'] doc = self.cleaned_data['document'] document = document(title = title, document = doc) document.save() return document
script:
<script type="text/javascript"> $("#uploadform").submit(function(event){ event.preventdefault(); $.ajax({ url : "{% url 'upload_document' %}", type: "post", data : {csrfmiddlewaretoken: document.getelementsbyname('csrfmiddlewaretoken')[0].value, title: document.getelementbyid('title').value, //document: document: document.getelementbyid('document'), }, datatype : "json", success: function( response ){ if(response == "true"){ // success } else { //append errors } } }); }); </script>
views.py
def upload_document(request): print request.post print request.files if request.is_ajax(): if request.method == 'post': form = uploadform(request.post, request.files, user = request.user) if form.is_valid(): form.save() return httpresponse(simplejson.dumps('true'), mimetype = 'application/json' ) else: errors = form.errors return httpresponse(simplejson.dumps(errors), mimetype = 'application/json' )
the answer question not simple. first of if intend support old browsers indeed gets nasty. have deal hidden iframes , javascript tricks. advice using well-known scripts jquery-file-upload.
but world evolving , new technologies arise including html5. there's new file api available in modern browsers ( ie10+, firefox3.6+, chrome13+, see: http://caniuse.com/fileapi ) can used that. first need html:
<input type="file" id="file-select" />
then can bind (for example) change
event:
$('#file-select').change( handlefileselect );
and handler itself:
var data = {}; function createreaderhandler(name) { return function(ev) { data[name] = ev.target.result; }; } function handlefileselect(ev) { var files = ev.target.files; // filelist object // loop through filelist (var = 0; < files.length; i++) { var file = files[i], name = file.name || file.filename, reader = new filereader(); reader.onload = createreaderhandler(name); reader.readastext(file); } }
once data loaded javascript memory (note operation asynchronous) can send via ajax other data. there more options: depending on file can read binary data using .readasbinarystring
, on. google friend. :)
also think there scripts uploading files fallback old methods. 1 can interesting (haven't tried it):
Comments
Post a Comment