title: Uploading Image Using JQuery And Django
body: <p>Before you continue reading, trust me when I say I have read all the other posts on this subject, and none of them helped.</p>
  
  <p>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.</p>
  
  <p>Here is what I have:</p>
  
  <p>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.</p>
  
  <pre><code>&lt;form id="add-picture-form" method="POST" action="/api/upload_image/" enctype="multipart/form-data"&gt;{% csrf_token %}  
      &lt;div class="thumbnails" style="width:400px;"&gt;
          &lt;label class="cabinet BrandHeader"&gt; 
              &lt;input type="file" class="file" id="upload-photo" onChange="$('#add-picture-form').submit();" /&gt; 
          &lt;/label&gt; 
      &lt;/div&gt;
  &lt;/form&gt; 
  </code></pre>
  
  <p>Jquery:</p>
  
  <pre><code>$('#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;   
  }); 
  </code></pre>
  
  <p>Finally my django view that is hit when you post to /api/upload_image/</p>
  
  <pre><code>def ajax_upload( request ):
  
      print request.POST
      print request.FILES
  
      return http.HttpResponse(simplejson.dumps([True]), mimetype='application/javascript')
  </code></pre>
  
  <p>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.</p>