Is it possible to post image file using the jQuery's ajax post method. Would it work if I just put the file data in the POST request's 'data' parameter?
I am using django framework. This is my first attempt:
$('#edit_user_image').change(function(){ var client = new XMLHttpRequest(); var file = document.getElementById("edit_user_image"); var csrftoken = document.getElementsByName('csrfmiddlewaretoken')[0].value /* Create a FormData instance */ var formData = new FormData(); formData.append("upload", file.files[0]); client.open("post", "/upload-image/", true); client.setRequestHeader("X-CSRFToken", csrftoken); client.setRequestHeader("Content-Type", "multipart/form-data; charset=UTF-8; boundary=frontier"); client.send(formData); /* Send to server */ }); The problem with this is that I don't get the'request.FILES' object on the serer side in my 'views.py'.
I also tried doing it with ajax post but it doesn't work either.
$('#edit_user_image').change(function(){ var data = {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, content:document.getElementById("edit_user_image").files[0],} $.post("/upload-image/", data, function(){ }); }); Edit from one of the answers:
$('#edit_user_image').change(function(){ var formData = new FormData($("#edit_user_image")[0]); $.ajax({ type: "POST", url: "/upload-image/", xhr: function() { // custom xhr // If you want to handling upload progress, modify below codes. myXhr = $.ajaxSettings.xhr(); if(myXhr.upload){ // check if upload property exists myXhr.upload.addEventListener('progress', yourProgressHandlingFunction, false); // for handling the progress of the upload } return myXhr; }, data: formData, // Options to tell JQuery not to process data or worry about content-type cache: false, contentType: false, processData: false, beforeSend: function(xhr) { // If you want to make it possible cancel upload, register cancel button handler. $("#yourCancelButton").click(xhr.abort); }, success: function( data ) { // Something to do after upload success. alert('File has been successfully uploaded.'); location.reload(); }, error : function(xhr, textStatus) { // Something to do after upload failed. alert('Failed to upload files. Please contact your system administrator. - ' + xhr.responseText); } }); });