2013-11-05 3 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"; 끝에'$ upload_path = "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를 어디에서 아약스 요청으로 전달하고 있는가? (나는 단지 이것이 어떻게 작동하는지 이해하려고 노력하고있다.) – Andrew

+0

이것은 기본적으로 이것을 특정 형식으로 보내고있는 것이 아니다. 'formData.append ("file", transcript); 단계는이 작업을 수행합니다. 그리고 아약스에서는'data : { 파일 : 파일 이름 : 데이터 : 데이터 : },'로 전달합니다. 'file : filename'을 말한 행에 대해 –

+0

이 있는데, 거기에 뭔가 있어야할까요? 나는 더 이상 제출하지 않는 양식을 제외하고 그것을 달렸다. – Andrew

0

첫째, 당신의 코드에서 $.ajax({...}) 데이터를 게시하고, 전송 된 데이터는

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

가 전혀 transcript 없습니다입니다.

둘째, 가장 중요한 것은 $.ajax({...})과 같은 파일을 게시 할 수 없기 때문에 그렇게 작동하지 않습니다. @Roy MJ가 말했듯이 FormData (최근 브라우저 만 해당)를 보거나 업로드 jQuery 플러그인을 웹에서 살펴보아야합니다 (whell을 다시 작성하지 말고 일부 좋은 플러그인은 이미 존재합니다 :))

이 당신을 위해 그것을해야 살펴에게 here

0

당신이 HTML 요소의 값처럼 당신은 파일을 보낼 수 없습니다. 파일 업로드에는 두 가지 방법이 있습니다. 성공적으로 사용한 방법은 AjaxUploader라는 타사 기능을 사용하는 AJAX 방법입니다. GitHub를 통해 download it here을 사용할 수 있습니다. 일단 당신이 'js'폴더 (또는 모든 스크립트 파일을 넣은 곳)에 ajaxuploader.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 : 문제가 해결되면 답변으로 표시하는 것을 잊지 마십시오.

관련 문제