我有一个 js 页面,它使用 AJAX 来获取 <input type="file" />
中提供的图像。 ,通过 POST 将其发送到 php 页面(upload.php)。 jQuery 按预期运行,成功运行时的代码,我知道,因为我得到 alert("Success");
。因此我相信问题出在我的 PHP 页面上。文件显示如下。提前致谢。
HTML:
<form id='uploadimage' method='post' enctype='multipart/form-data'>
<div id='selectImage'>
<input type='file' name='file' id='file' required />
<input type='button' id='imageUpload' value='Upload' class='submit' />
</div>
</form>
jQuery:
$(document).ready(function (e) {
$("#imageUpload").on('click',(function(e) {
e.preventDefault();
$('#loading').show();
$.ajax({
url: "upload.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function() { // A function to be called if request succeeds
alert("success");
$('#loading').hide();
}
});
}));
});
PHP:
<?php
if(isset($_FILES["file"]["type"])) {
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000000)
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else {
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
最佳答案
看起来您没有使用 $.ajax() 发送文件(或任何其他表单数据)。
您可以使用 FormData 对象,它可以让您编译一组键/值对(包括文件输入)以通过 ajax 发送。如果表单的编码类型设置为 multipart/form-data,则传输的数据与表单的提交方法用于发送数据的格式相同。 https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
关于javascript - PHP 和 jQuery 与 AJAX 上传不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31298316/