我正在一个项目中,要求将PDF文件以文件格式上传到服务器,例如/home/xyz/proect_dir/upload/file_name.pdf
,并将文件路径存储到MySQL数据库。我正在使用PHP和AJAX上传PDF文件。我收到以下错误。
注意:未定义索引:uploaded_pdf
这是我的代码:
upload.html
<form action="#" method="post" id="frm_upload_pdf" enctype="multipart/form-data">
<input type="file" name="uploaded_pdf" id="uploaded_pdf" accept="application/pdf" class="upload" />
<button type="submit" id="btnUploadPaper">Save</button>
</form>
upload.js
$('#frm_upload_pdf').validate({
rules: {
uploaded_pdf: { required: true }
},
messages: {
uploaded_pdf: { required: "Select pdf file" }
},
errorPlacement: function(error, element) {
error.insertAfter(element);
},
submitHandler: function() {
uploadPDF();
}
});
function uploadPDF() {
$.ajax({
url: 'upload_processor.php',
type: 'POST',
data: $('#frm_upload_pdf').serialize(),
success: function (data) {
alert(data);
}
});
}
upload_processor.php
public function uploadPaper() {
$fileName = $_FILES['uploaded_pdf']['name'];
$temp_name = $_FILES['uploaded_pdf']['tmp_name'];
if (isset($fileName)) {
if (!empty($fileName)) {
$fileType = pathinfo(FILE_UPLOAD_ROOT.$fileName, PATHINFO_EXTENSION);
$allowTypes = array('pdf');
if (in_array($fileType, $allowTypes, true)) {
//upload file to server
return move_uploaded_file($temp_name, FILE_UPLOAD_ROOT.$fileName) ? true : false;
}
return false;
}
return false;
}
return false;
}
在调试时,我发现ajax不会将文件数据发布为$_FILES
,因此它给出了以上未定义索引的错误。不知道为什么它不将文件数据发布为$_FILES
还是我在这里丢失了任何内容。
答案 0 :(得分:0)
我已经如下重新编写了您的ajax和php代码。
首先,您需要在PHP代码所在的目录中创建一个名为 pdf 的文件夹。
在下面运行以下经过测试的代码及其工作。让我知道它对您有用
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload_processor.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
$("#errorLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
</head>
<body>
<div>
<form id="uploadForm" action="upload_processor.php" method="post">
<div id="targetLayer"></div>
<div id="errorLayer"></div>
<div id="uploadFormLayer">
<input name="uploaded_pdf" type="file" class="inputFile" /><br/>
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</div>
</body>
</html>
php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['uploaded_pdf']['tmp_name'])) {
$fileName = $_FILES['uploaded_pdf']['name'];
$sourcePath = $_FILES['uploaded_pdf']['tmp_name'];
$targetPath = "pdf/".$_FILES['uploaded_pdf']['name'];
if($fileName ==''){
echo "<div id='errorLayer'>Please select file</div>";
exit;
}
$fileType = pathinfo($fileName, PATHINFO_EXTENSION);
$allowTypes = array('pdf');
if (!in_array($fileType, $allowTypes, true)) {
echo "<div id='errorLayer'>File type is invalid</div>";
exit;
}
if(move_uploaded_file($sourcePath,$targetPath)) {
echo "<div id='targetLayer'>File uploaded successfully</div>";
?>
<?php
}
}
}
?>