Php 通过ajax上传文件
我正在尝试使用ajax上传文件Php 通过ajax上传文件,php,ajax,Php,Ajax,我正在尝试使用ajax上传文件 form enctype="myltipart/form-data" id="pastTest-form" method="POST" action="upload.php"> <div class="feedback-form-inputs col-5"> <div class="input-field"> <select id="
form enctype="myltipart/form-data" id="pastTest-form" method="POST" action="upload.php">
<div class="feedback-form-inputs col-5">
<div class="input-field">
<select id="type" required>
<option value="quiz">Quiz</option>
<option value="midterm">Midterm</option>
<option value="final">Final</option>
</select>
</div>
<div class="input-field">
<input type="text" id="professor"/>
</div>
<div class="input-field">
<input type="text" id="name"/>
</div>
<div class="input-field">
<input type="file" id="uploaded_file" name="file" accept="" required />
</div>
</div><!-- END feedback-form-inputs -->
<div class="clear"></div>
<input type="submit" value="submit" onclick="submit() />
<div id="upload-status"> </div>
</form>
因此,我将formData发送到php。但此时,我无法从表单数据中获取文件并将其上载到服务器。
这是我的php
// Ajax calls this code to add a past test
if (isset($_FILES['file']){
$file = $_FILES['file'];
$path = 'files/'.$type.'/'.$fileName;
$moveResult = move_uploaded_file($file, $path);
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
//unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
$path = 'files/'.$type.'/'.$fileName;
$sql = "INSERT into past_papers VALUES ('$name', '$type', '$cid', '$professor','$path')";
$query = mysqli_query($db_conx,$sql);
if (mysqli_affected_rows($db_conx)>0){
echo "success";
exit();
}
else {
echo "failed sql";
exit();
}
}
?>
此外,我想抓取文件的输入,并一起处理它们。上传文件,并将输入插入数据库。我能找到的最简单的一个。:) jQuery代码 HTML代码
您应该使用搜索功能,大量的帖子都与此相关。例如,您的上传处理完全无效。您需要首先检查$\u FILES['file']['error']
,以查看上载是否已意外执行并成功。你只是简单地假设没有什么会出错,而这恰恰是错误的做法。
// Ajax calls this code to add a past test
if (isset($_FILES['file']){
$file = $_FILES['file'];
$path = 'files/'.$type.'/'.$fileName;
$moveResult = move_uploaded_file($file, $path);
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
//unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
$path = 'files/'.$type.'/'.$fileName;
$sql = "INSERT into past_papers VALUES ('$name', '$type', '$cid', '$professor','$path')";
$query = mysqli_query($db_conx,$sql);
if (mysqli_affected_rows($db_conx)>0){
echo "success";
exit();
}
else {
echo "failed sql";
exit();
}
}
?>
$("#form-id").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "file-to-call.php",
type: "POST",
data: new FormData(this),
cache: false,
processData: false,
success: function(data) {
//handle success
}
});
}));
<form name='form1' method='post' enctype='multipart/form-data' id='form-id'>
<input type='submit' id='input' value='Upload' />
</form>