0

I tried to submit this form using ajax ,sothat a django view can extract the selected file from request.FILES and write to a directory on server

<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> 

the view is

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")

I used jquery to make the ajax submit

$(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);   
}

when I tried this ,I got this console output

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

I sense that I am doing something wrong in the django view..Is it that I cannot get the uploaded file from request.FILES.In a non ajax version of django view ,I was able to get the file from request.FILES using request.FILES['fselect']

Can somebody help me resolve this?

2
  • Which js library do you use to help uploading? Commented Jun 1, 2012 at 9:29
  • @okm ,only jquery and the above script Commented Jun 1, 2012 at 9:54

1 Answer 1

1

I don't think you can do ajax file uploads (easily).

Certainly, it doesn't look like you're actually passing a file to your post data, you're just passing the file name -

var data = { name:file.name };

Check out this question for plugins / info to help do this - How can I upload files asynchronously?

Sign up to request clarification or add additional context in comments.

3 Comments

that data was passed just for testing purposes.A normal form submit has the file data in request.FILES ,why is it that when submit is done thru ajax ,it is missing?
I think you need to show how "submit is done thru ajax". The fact that the file isn't in request.FILES, suggests it's the javascript that's broken, not the django. What is the code that actually submits the file?
thanks @Aidan for the reply..finally I got this working by using formData and XMLHttpRequest.send..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.