我目前正在尝试使用jQuery通过我制作的表单上传文件。这就是我想要做的事情:
function ajax_upload(){
var formData = new FormData($('form#userform'));
$.ajax({
url: location.protocol + "//" + location.host + "/profile/uploadPicture",
dataType: 'json',
data: formData,
type: 'post',
success: function(data, status){
if (data.status == 'error') {
$('#error').html(data.msg);
}
else {
var filename = location.protocol + "//" + location.host + "/data/profiles/" + data.msg;
$('input#filename').val(filename);
close_upload_form();
pop_profilechanger(filename);
}
}
});
return false;
}
表单似乎发布到后端,但在尝试从JSON对象中的上传文件返回文件名时,如: echo json_encode(array('status'=> $ status,'msg'=> $ msg));
有什么问题吗? 请告诉我
答案 0 :(得分:0)
我就是这样做的。如果您想了解更多信息,而不仅仅是我粘贴的代码,请查看此http://www.html5rocks.com/en/tutorials/file/dndfiles/,因为我的代码是为拖放文件而制作的
handleFiles : function(files, evt, target)
{
console.log(target);
$.each(files, function(index, value)
{
var file = value;
reader = new FileReader();
reader.onload = function(evt)
{
var li = $("<li class='uploading'><img data-image-id='0' src='" + evt.target.result + "' /></li>");
target.find('.imagesList').append(li);
var request = new XMLHttpRequest();
var formData = new FormData();
formData.append('image', file);
request.open("Post", settings.uploadImageUrl);
request.addEventListener("load", function(evt)
{
var id = evt.target.responseText;
li.removeClass('uploading');
li.find('img').attr('data-image-id', id);
}, false);
request.send(formData);
};
reader.readAsDataURL(value);
});
},