josephmisiti
josephmisiti

Reputation: 9974

Uploading Image Using JQuery And Django

Before you continue reading, trust me when I say I have read all the other posts on this subject, and none of them helped.

I am trying to add image upload functionality to my website. I want to upload the image via an ajax post. I cannot get this working.

Here is what I have:

HTML - i have a special setup so that an image is displayed instead of a stupid button and the text field. I am also using the onChange event to automatically submit when I have hit "OK" after selecting the image.

<form id="add-picture-form" method="POST" action="/api/upload_image/" enctype="multipart/form-data">{% csrf_token %}  
    <div class="thumbnails" style="width:400px;">
        <label class="cabinet BrandHeader"> 
            <input type="file" class="file" id="upload-photo" onChange="$('#add-picture-form').submit();" /> 
        </label> 
    </div>
</form> 

Jquery:

$('#add-picture-form').submit(function() { 
    //var filename = $("#upload-photo").val();
    var photo = document.getElementById("upload-photo"); 
    var file  = photo.files[0];

$.ajax({ 
    type: "POST",
    url: "/api/upload_image/",
    enctype: 'multipart/form-data',
    data: {'file': file.getAsBinary(), 'fname' : file.fileName },
    success: function(){
       alert( "Data Uploaded: ");
    }
});

    return false;   
}); 

Finally my django view that is hit when you post to /api/upload_image/

def ajax_upload( request ):

    print request.POST
    print request.FILES

    return http.HttpResponse(simplejson.dumps([True]), mimetype='application/javascript')

I have tried to write the image to binary, but I cannot open that data that has written. Why is uploading an image using javascript so hard? I am an idiot and just not using a simple solution? If so, please tell me what is the best way to use jQuery to upload an image in Django.

Upvotes: 8

Views: 11243

Answers (2)

Scott Stafford
Scott Stafford

Reputation: 44838

Try the jQuery plugins Uploadify or SWFUpload. Someone even did the Django integration for you, see: https://github.com/tstone/django-uploadify and http://blog.fogtunes.com/2009/11/howto-integrate-swfupload-with-django/.

Upvotes: 5

ddango
ddango

Reputation: 956

I'm not that familiar with django but I think the issue is that uploading a file via AJAX isn't as simple as you might think.

There are several methods of getting around this, but I recommend using one that already exists. Since you are using jquery, I would recommend the jquery forms plugin: http://jquery.malsup.com/form/#getting-started

The plugin supports file uploading out of the box, and really all you'll need to do is wire it up to your form:

$('#add-picture-form').ajaxForm();

see also: How can I upload files asynchronously?

Upvotes: 2

Related Questions