0

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;
}
damon
  • 8,127
  • 17
  • 69
  • 114

1 Answers1

1

For the simple answer, you don't. Send your form into an hidden iframe and and let the javascript call its parent window.

Since file uploading occurs through an iframe, traditional response data such as HTTP status codes are not directly available, and connection manager cannot reasonably discern success or failure (except a transaction timeout). Instead, the callback's upload handler will receive a response object containing the body of the iframe document, as a string, when the transaction is complete.

http://developer.yahoo.com/yui/connection/#upload

My advise is, find a decent library that does that for you and use it:

With recent browsers, it's possible to do it without relying on an iframe: Sending multipart/formdata with jQuery.ajax

Community
  • 1
  • 1
greut
  • 4,305
  • 1
  • 30
  • 49