2016-03-26 38 views
0

我試圖使用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的唯一原因是在收到響應後顯示模式對話框

+0

的一個問題,我看到你的名字越來越$的fileType你產生,而不是從你正在上傳的文件,它應該是這樣的'$ fileType = pathinfo($ _ FILES [「datafile」] [「tmp_name」],PATHINFO_EXTENSION);' – kunicmarko20

+0

謝謝,我會嘗試。但我也忘了提及,如果我使用表單,設置動作並使用提交按鈕,這可以很好地工作 –

+0

您不能以這種方式序列化文件。瀏覽器安全/沙盒不會允許它。你必須使用一些其他的解決方案,可能是使用iframe的東西。請參閱此鏈接(http://stackoverflow.com/a/4545089/1233305) – David784

回答

0

當您開始使用AJAX POST時,應該在$ _POST而不是$ _FILES中查找已發佈的參數。

這是因爲$ _FILES是通過多部分文章上傳的文件的緩存。既然你已經使用AJAX序列化併發送,PHP解析JSON,把裏面的東西$ _ POST

here爲例

+0

感謝您的回覆。我嘗試用$ _POST替換$ _FILES,但我仍然得到相同的錯誤 –

+0

@HenryJooste你可以嘗試平分你的PHP代碼,看看究竟哪一行導致了這個問題? –

+0

是的,我已經做到了。它在'move_uploaded_file'調用失敗。所以我確定它會獲取文件,因爲它通過了PDF文件擴展名檢查 –