【发布时间】:2020-03-14 03:45:30
【问题描述】:
我试图使用带有 jQuery 的 ajax() 函数的 php 在服务器上上传文件。下面是我正在尝试的代码。当我在没有 jQuery 的情况下在同一页面上编写 PHP 代码时,一切正常,所以毫无疑问,文件上传工作正常。
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function() {
$("form").submit(function(e){
e.preventDefault();
var fd = new FormData();
fd.append("files", $("#fileinput").prop("files"));
$.ajax({
url: "imgupload_.php",
type:"POST",
processData: false,
contentType: false,
data: fd,
success: function(result){
alert(result);
}
});
});
});
</script>
<form method="POST" action="#" enctype="multipart/form-data">
<input type='file' name='files' id="fileinput"/>
<input type='submit' value='Submit' name='submit'/>
</form>
imgupload_.php
if(isset($_POST["submit"])) {
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["files"]["name"]);
if (move_uploaded_file($_FILES["files"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["files"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
如果您想了解任何其他信息,请在下方评论。
【问题讨论】:
标签: php jquery ajax file-upload