难以理解如何访问type =" file"在服务器端输入。以下是我正在使用的代码。我使用AJAX是因为我希望我的网络应用程序不需要刷新,并且使用稍微迂回的方式提交表单,这样我就可以拥有更好的用户界面。
我的HTML:
<form id="updateProfileImageForm" enctype="multipart/form-data">
<div class="updateProfileImageContainer">
<img src="images/profile/generic.png" class="updateProfileImage">
<div class="updateProfileImageOverlay" onclick="changeImageToUpload()">
<div class="updateProfileImageOverlayText">Upload new image</div>
</div>
<input type="file" id="imageToUpload" name="image" style="display: none;" onChange="$(this).closest('form').trigger('submit');"></input>
</div>
</form>
我的JS:
function changeImageToUpload() {
$('#imageToUpload').trigger('click');
}
$('#updateProfileImageForm').submit(function(e) {
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
type: 'POST',
url: '/changeProfile',
data: form_data,
processData: false,
success: function(response) {
if(response.message != null) {
alert(response.message);
} else {
// Change profile image displayed
$('.updateProfileImage').attr("src", response.newProfileImage);
alert('Profile picture successfully updated! Refresh your browser to update your window!');
}
}
})
});
我的服务器PHP:
if (isset($_FILES['image'])) {
$image = $_FILES['image'];
}
$ _FILES上的Var_dump显示一个空数组,而$ _POST上的var_dump显示了很多信息(我假设它是我的数据文件)。但是,访问&#39;图像&#39; $ _POST或$ _FILES上的属性(通过$ _POST [&#39;图像&#39;]或$ _FILES [&#39;图像&#39;])给出了&#34;未定义的索引&#34;或&#34;未定义的变量&#34;。
你们会非常善良地教育我:
$ _POST和$ _FILES之间有什么区别?
在这种情况下我应该如何访问该文件?
谢谢!
答案 0 :(得分:0)
您在ajax请求中缺少必要的配置选项,您需要将contentType设置为false
$.ajax({
type: 'POST',
url: '/changeProfile',
data: form_data,
processData: false,
contentType: false,
success: function(response) {
if(response.message != null) {
alert(response.message);
} else {
// Change profile image displayed
$('.updateProfileImage').attr("src", response.newProfileImage);
alert('Profile picture successfully updated! Refresh your browser to update your window!');
}
}
})
jQuery.ajax默认情况下将内容类型设置为application / x-www-form-urlencoded,这对于FormData对象是不正确的,如果将其设置为false,它将由底层XMLHTTTPRequest对象正确设置。
答案 1 :(得分:-1)
背后的理念。 而不是使用文件作为发布到PHP,只需将图像转换为base64并使用php中的ajax接收该字符串。