I am sending an image file using XMLHttpRequest() in my Django app. This is my script:
$('#edit_user_image').change(function(){
var client = new XMLHttpRequest();
var file = document.getElementById("edit_user_image");
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append("csrfmiddlewaretoken", document.getElementsByName('csrfmiddlewaretoken')[0].value);
formData.append("upload", file.files[0]);
client.open("post", "/upload-image/", true);
client.setRequestHeader("Content-Type", "multipart/form-data; charset=utf-8; boundary=frontier");
client.send(formData); /* Send to server */
});
This is my html input:
Upload New Photo
{% csrf_token %}
<input id="edit_user_image" name="image" type="file" />
But, when the XMLHttpRequest() is made, it give "CSRF verification failed" error even though I am appending it in the data. Can anyone tell what is wrong in the script.
Here are some of the changes that I made and now its working fine:
$('#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 params = 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(params); /* Send to server */
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.