我试图在文件图片名称更改时使用ajax上传图片,但我无法在服务器端获取$_FILES["InputUploadFileImage"]["tmp_name"];
我的代码。
JQuery代码
$('#InputUploadFileImage').change(function() {
var FilePath = $('#InputUploadFileImage').val();
var FileSize = this.files[0].size;
$.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
type: "POST",
action: 'Ajax_ChangingProfileImage',
FilePath: FilePath,
FileSize: FileSize
}),
success: function (response) {
if (response.Message === 'ImageSuccessfullyUploaded') {
alert('Image Successfully Uploaded.');
$('#imgUserImage').image_src = FilePath;
console.log(response.FilePath);
} else {
alert('Image was not uploaded successfully.');
$('#imgUserImage').image_src = FilePath;
console.log(response.FilePath);
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
});
PHP代码
function Ajax_ChangingProfileImage() {
$FileTmpPath = $_FILES["InputUploadFileImage"]["tmp_name"];
$FileSize = $_POST['FileSize'];
$FilePath = $_SERVER['DOCUMENT_ROOT'] . "restronaut/wp-content/uploads/UsersImages/1.jpg";
$IsUploaded = move_uploaded_file($FileTmpPath ,$FilePath);
if ($IsUploaded) {
$response['Message'] = 'ImageSuccessfullyUploaded';
$response['FilePath'] = $FilePath;
} else {
$response['Message'] = 'ImageNotSuccessfullyUploaded';
$response['FilePath'] = $FilePath;
}
header('Content-Type: application/json');
echo json_encode($response);
die();
}
请任何帮助,并提前多多感谢..
答案 0 :(得分:1)
您需要使用 new formData()来使用ajax调用发送图像。 这等于以常规形式设置enctype(没有ajax)
有关formData对象here's a MDN link for you.
的更多信息JQuery代码
$('#InputUploadFileImage').change(function() {
/*var FilePath = this.files[0];
var FileSize = this.files[0].size;
var file = this.files[0];
var name = FilePath.name;
var type = FilePath.type;*/
var formData = new FormData($('*formId*')[0]);
$.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
type: "POST",
action: 'Ajax_ChangingProfileImage',
formData : formData
}),
success: function (response) {
if (response.Message === 'ImageSuccessfullyUploaded') {
alert('Image Successfully Uploaded.');
$('#imgUserImage').image_src = FilePath;
console.log(response.FilePath);
} else {
alert('Image was not uploaded successfully.');
$('#imgUserImage').image_src = FilePath;
console.log(response.FilePath);
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
});
PHP代码
print_r($_FILES);
答案 1 :(得分:0)
我担心你无法通过JavaScript获取文件上传框的值。因此,您无法通过Ajax以与标准文本数据相同的方式提交文件上载。
相反,您必须使用JavaScript的FormData
对象将文件包装到multipart/form-data
发布数据对象中。请参阅StackOverflow问题中接受的答案:
Upload File With Ajax XmlHttpRequest
请注意,Internet Explorer 9不支持FormData
API。