FormData file upload to Django model?
I'm trying to upload a file through a jQuery ajax request, using FormData
. When I set processData
and contentType
to false
, I get the error Forbidden (CSRF token missing.)
. When I remove those, I get the error Uncaught TypeError: 'slice' called on an object that does not implement interface Blob.
.
What am I missing here?
$(".form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "/upload_profile_pic/",
type: "POST",
processData : false,
contentType : false,
data: { "profile_pic": formData.get("file"), "csrfmiddlewaretoken": $(this).find("input[name='csrfmiddlewaretoken']").val() },
},
success: function (data) {
console.log("success: "+data);
},
error: function (data) {
console.log(data);
}
});
});
Sorry, I already found the answer here. You have to use cache : false
and then it works!
formData.append("profile_pic", file);
//...
formData.append("csrfmiddlewaretoken", $(this).find("input[name='csrfmiddlewaretoken']").val());
$.ajax({
url: action,
type: "POST",
data: formData,
cache : false,
processData : false,
contentType : false,
success: function (data) {
console.log("success"+data);
},
error: function (data) {
console.log(data);
}
});