2013-11-05 27 views
0

我一直在試圖創建一個註冊表單,要求學生在最後上傳文檔。但是,通過jQuery獲取表單值後,PHP文檔似乎無法獲取我上傳的表單。有任何想法嗎?PHP不能拿起文件

形式:

<form id="joinUs" enctype="multipart/form-data" method="post"> 
    <!--various form fields--> 
    <input type="file" name="transcript" id="transcript"> 
    <div class="button" id="submit">Submit!</div> 
</form> 

的jQuery:

$("#submit").click(function(){ 
    //firstName, lastName, grade, studentID, email, phone are all form values 
    var data = "firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone; 
     $.ajax({ 
          type: "POST", 
          url: "join_submit.php", 
          data: data, 
          success: function() {           
            location.href="http://mvcsf.com/new/success.php"; 

          } 
        }); 

join_submit.php

$allowedExtensions = array("pdf"); 
$max_filesize = 20000; 
$upload_path = "docs/transcripts"; 
$filename = $_FILES["transcript"]["name"];   
$filesize = $_FILES["transcript"]["size"]; 
$extension = $_FILES["transcript"]["type"]; 
if ($_FILES["transcript"]["error"] > 0) { 
     echo "Error: " . $_FILES["transcript"]["error"] . "<br />"; 
    } 
else if((in_array($extension, $allowedExtensions)) && ($filesize < $max_filesize)) { 
    move_uploaded_file($_FILES["transcript"]["tmp_name"], $upload_path . $filename); 
} 

我跑了這一點,我沒有錯誤。我也嘗試打印出文件名,除了沒有打印出來。

+0

可能重複的[我怎樣才能上傳文件與jQuery異步?](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) – hjpotter92

+1

您需要以FormData()方式傳遞文件。否則文件不會在另一端獲得 –

+0

想到的唯一的東西是,你測試了一個大於或小於'20000'的文件嗎?這不是很大,20,000字節。如果是這樣,那麼這是停止上傳的一件事。其次,嘗試在'$ upload_path =「docs/transcripts」;''''uploadspath =「docs/transcripts /」;「''末尾添加正斜槓並確保該文件夾具有寫入權限,夾。 –

回答

0

這應該爲你做它:

$("#submit").click(function() { 

     var transcript = $("#transcript").val(); 

     var data = "firstName=" + firstName + "&lastName=" + lastName + "&grade=" + grade + "&studentID=" + studentID + "&email=" + email + "&phone=" + phone; 
     var formData = new FormData(); 

     formData.append("file", transcript); 
     formData.append("data", data); 

     $.ajax({ 
      type: "POST", 
      url: "join_submit.php", 
      enctype: 'multipart/form-data',//optional 
      cache: false, 
      contentType: false, 
      processData: false, 
      data: { 
       file: file 
       data: data 
      }, 
      success: function() { 
       location.href = "http://mvcsf.com/new/success.php"; 

      } 
     }); 
}); 

乾杯

+0

複製瀏覽器功能謝謝!我會稍後再嘗試一下並回復你。雖然我有一個問題 - 你在哪裏將formData傳遞給ajax請求? (我只是想了解它是如何工作的) – Andrew

+0

不,這基本上只是以特定的格式發送出去。 formData.append(「file」,transcript);'這樣做。在ajax中,您將它傳遞爲'data:{ file:filename data:data },'。 –

+0

表示'file:filename'的行,是否應該有別的東西呢?我跑了它,除了表格不再提交 – Andrew

0

首先,在代碼中,你與$.ajax({...})發佈的數據和發送的數據是

"firstName="+firstName+"&lastName="+lastName+"&grade="+grade+"&studentID="+studentID+"&email="+email+"&phone="+phone; 

沒有transcript可言。

其次,最重要的是,你不能像$.ajax({...})那樣發佈文件,它不會像那樣工作。正如@Roy MJ所說的,你應該看一下FormData(僅適用於最近的瀏覽器),或者在Web上查看上傳的jQuery插件(不要重新發明這個插件,一些好的插件已經存在:))

看看here

0

像你這樣的HTML元素的值,你不能發送文件。有兩種文件上傳方式,我成功使用的方法是使用稱爲「AjaxUploader」的第三方功能的AJAX方法。您可以通過GitHub使用download it here。完成之後,將ajaxuploader.js文件添加到「js」文件夾中(或將所有腳本文件放在任何位置),將文件包含在要使用上傳器的HTML頁面中。現在,上傳過程非常簡單,如下所示。
HTML:

<input type="file" name="transcriptUploader" id="transcriptUploader" value="Upload" /> 

的jQuery(你需要有包含在你頁面jQuery的文件):

  new AjaxUpload('transcriptUploader', { 
      action: "page_to_handle_upload.php", // You need to have either a separate PHP page to handle upload or a separate function. Link to either one of them here 
      name: 'file', 
      onSubmit: function(file, extension) { 
       // This function will execute once a user has submitted the uploaded file. You can use it to display a loader or a message that the file is being uploaded. 
      }, 
      onComplete: function(file, response) { 
       // This function will execute once your file has been uploaded successfully. 
       var data = $.parseJSON(response); // Parsing the returning response from JSON. 
       if(data.error == 0) 
       { 
        // If the file uploaded successfully. 
       } 
       else if(data.error == "size"){ 
        // If the response object sent 'size' as the error. It means the file size exceeds the size specified in the code. 
       } 
       else if(data.error == "type"){ 
        // If the response object sent 'type' as the error. It means the file type is not of that specified in the code (in your case, pdf). 
       } 
       else{ 
        // In case the file didn't upload successfully or the code didn't return a usual error code. It is still an error so you need to deal with it appropriately. 
       } 

      } 
     }); 

後端PHP代碼,將會做所有繁重的任務(上傳文件,檢查擴展名,移動它等):

if(isset($_FILES)) // Checking if a file is posted. 
{ 
    if ($_FILES['file']['error'] == 0) //Checking if file array contain 0 as an error. It means AJAX had no error posting the file. 
    { 
     $response = array(); // Initializing a new array. 
     $allowedExts = array("pdf"); // Allowable file format. 
     $filename = stripslashes($_FILES['file']['name']); // Storing file name. 
     //$extension = strtolower(self::_getExtension($filename)); // Fetching file extension. 
     // Code block to extract file extension and storing it in a variable called $extraction. 
     $i = strrpos($str, "."); 
     if (!$i) 
     { 
      $extension = ""; 
     } 
     $l = strlen($str) - $i; 
     $extension = strlower(substr($str, $i + 1, $l)); 
     $size = $_FILES['file']['size']; // Storing file size (in bytes). 
     $fileNameAfterUpload = md5((time() + microtime())) . '.' . $extension; // Concatinating file name and extension. 
     $baseSystemPath = "/var/www/<your_folder_name>/uploaded_transcripts/" // Path on which the file will be uploaded. Need to be relative web path. 
     $maxSize = 10*10*1024; // Storing file size. Be advised the file size is in bytes, so this calculation means max file size will be 10 MB. 
     $webPath = "uploaded_transcripts/". $filename; // Creating web path by concatinating base web path (the folder in which you'd be uploading the pdf files to) with file name. 


     if (in_array($extension, $allowedExts)) // Checking if file contains allowabale extensions. 
     { 
      if($size <= $maxSize) // Checking if the size of file is less than and equal to the maximum allowable upload size. 
      { 
       $moved = move_uploaded_file($_FILES['file']['tmp_name'], $webPath); // Moving the file to the path specified in $webPath variable. 
       if($moved == true) 
       { 
        $response['error'] = 0; // If moved successfully, storing 0 in the response array. 
        $response['path'] = $webPath; // Storing web path as path in the response array. 
        $response['filename'] = $filename; // Storing file name in the response array. 
       } 
       else 
      { 
        $response['error'] = 'internal'; // If move isn't successfull, return 'internal' to AJAX. 
       } 
      } 
      else 
      { 
       $response['error'] = 'size'; // If file size is too small or large, return 'size' to AJAX. 
      } 
     } 
     else 
     { 
      $response['error'] = 'type'; // If file type is not that of defined, return 'type' to AJAX. 
     } 
     echo json_encode($response); // Returning the response in JSON format to AJAX. 
    } 
} 

請告訴我,如果您需要進一步的幫助。 P.S:不要忘了標記它作爲一個答案,如果它的工作。