damon
damon

Reputation: 8487

django view cannot get file using request.FILES from ajax form submit

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?

Upvotes: 0

Views: 2484

Answers (1)

Aidan Ewen
Aidan Ewen

Reputation: 13328

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?

Upvotes: 1

Related Questions