我試圖使用AJAX上傳PDF文檔,但它始終以未知的錯誤失敗。我究竟做錯了什麼?使用AJAX上傳PDF
HTML文件:
<form id="document">
<p>
Title<br>
<input type="text" name="name" size="30">
</p>
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input id="submit-button" type="button" value="Send">
</div>
</form>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#submit-button').click(function() {
$.ajax({
type: "POST",
dataType: "JSON",
url: "upload_document.php",
data: $("#document").serialize(),
success : function(data){
alert(data.message);
}, error : function(data) {
alert(data.message);
}
});
});
});
</script>
PHP文件(upload_document.php)
<?php
header("Access-Control-Allow-Origin: *");
try {
$id = "[RANDOM_GENERATED_GUID]";
$targetDir = "../../../../modules/sites/documents/";
if (!is_dir($targetDir)) {
if (!mkdir($targetDir, 0777, true)) {
throw new Exception("Unable to upload your document. We were unable to create the required directories");
}
}
$targetFile = $targetDir . $id . ".pdf";
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);
if (file_exists($targetFile)) {
throw new Exception("Unable to upload your document. The file already exists");
}
if ($_FILES["datafile"]["size"] > 2000000) {
throw new Exception("Unable to upload your document. The file is to large (Maximum of 2MB)");
}
if ($fileType != "pdf") {
throw new Exception("Unable to upload your document. Only PDF documents can be uploaded");
}
if (!move_uploaded_file($_FILES["datafile"]["tmp_name"], $targetFile)) {
//Keeps failing here with error code 0
throw new Exception("Unable to upload your document. There was an error uploading the file");
}
echo json_encode(array(
"error" => false,
"message" => "Your document was successfully uploaded"
));
} catch (Exception $ex) {
echo json_encode(array(
"error" => true,
"message" => $ex->getMessage()
));
}
我還檢查了服務器上,並正在順利創建的目錄。謝謝您的幫助!
編輯
如果我設置窗體上的動作,並使用一個提交按鈕這完全一樣的PHP腳本。我想使用AJAX的唯一原因是在收到響應後顯示模式對話框
的一個問題,我看到你的名字越來越$的fileType你產生,而不是從你正在上傳的文件,它應該是這樣的'$ fileType = pathinfo($ _ FILES [「datafile」] [「tmp_name」],PATHINFO_EXTENSION);' – kunicmarko20
謝謝,我會嘗試。但我也忘了提及,如果我使用表單,設置動作並使用提交按鈕,這可以很好地工作 –
您不能以這種方式序列化文件。瀏覽器安全/沙盒不會允許它。你必須使用一些其他的解決方案,可能是使用iframe的東西。請參閱此鏈接(http://stackoverflow.com/a/4545089/1233305) – David784