【发布时间】:2014-01-10 00:33:18
【问题描述】:
是否可以使用 jQuery 的 ajax 发布方法发布图像文件。如果我只是将文件数据放在 POST 请求的 'data' 参数中,它会起作用吗?
我正在使用 django 框架。这是我的第一次尝试:
$('#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 */
});
问题在于我在“views.py”的服务器端没有得到“request.FILES”对象。
我也尝试过使用 ajax 发布,但它也不起作用。
$('#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_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);
}
});
});
【问题讨论】:
-
你试过了吗?发生了什么?
-
“发布”请求永远不会发生。
-
您确实需要提供更多信息。你想达到什么目的?如果您对图像文件进行了 base64 编码,则可以发布图像文件,但您需要服务器才能期待 base64。只需填写一些空白,我们会为您提供帮助。
标签: javascript python django xmlhttprequest