2017-09-18 1 views
1

formdata로 파일을 업로드하려고합니다. 파일 만 작동하지만 일부 사용자 데이터를 업로드해야합니다. 나는 formdata를 추가하려했지만, "print_r"배열 ($ _ FILES)이 아약스에 의해 호출 된 php 파일에 나타나지 않습니다.다중 자료 파일 업로드 (formdata)

누군가가 문제에 대한 해결책을 가지고 있거나 더 나은 방법으로 userdata로 파일 업로드를 해결하려는 경우 알려 주시기 바랍니다.

당신이 사용하는 코드를 찾을 수 있습니다 아래 :

PHP :

<!DOCTYPE html> 
<html lang="en"> 
<head> 
<meta charset="UTF-8"> 
<link href="style.css" rel="stylesheet" type="text/css"> 
<script src="jquery-1.12.0.min.js"></script> 


</head> 
<body> 
<div class="container"> 
    <h1>AJAX File upload</h1> 

    <form method="post" action="" enctype="multipart/form-data" id="myform"> 
     <input type="text" id="test" value="sample"> 
     <div > 
      <img src="" id="img" width="100" height="100"> 
     </div> 
     <div > 
      <input type="file" id="file" name="file" /> 
      <input type="button" class="button" value="Upload" id="but_upload"> 
     </div> 
    </form> 
</div> 
</body> 
<script type="text/javascript"> 
$(document).ready(function(){ 
    $("#but_upload").click(function(){ 
     //console.log("piemel"); 
     console.log(document.getElementById('test').value); 
     var fd = new FormData(); 
     var files = $('#file')[0].files[0]; 
     fd.append('test', document.getElementById('test').value); 
     fd.append('file',files); 
     console.log(fd); 

     $.ajax({ 
      url:'upload.php', 
      type:'post', 
      data:fd, 
      contentType: false, 
      processData: false, 
      success:function(response){ 
       if(response != 0){ 
        $("#img").attr("src",response); 
       } 
      }, 
      error:function(response){ 
       alert('error : ' + JSON.stringify(response)); 
      } 
     }); 
    }); 
}); 


</script> 
</html> 

아약스 파일 :

<?php 

/* Getting file name */ 

$filename = $_FILES['file']['name']; 

/* Location */ 
$location = "upload/".$filename; 

/* Upload file */ 
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){ 
    echo $location; 
}else{ 
    echo 0; 
} 

답변

1

데모 코드 작업 예제가 있습니다. 이

index.php를

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

<form id="uploadForm" action="upload.php" method="post"> 
<label>Upload Image File:</label><br/> 
<input name="userImage" type="file" class="inputFile" /> 
<input type='text' name="my_name" value="harish"> 
<input type="submit" value="Submit" class="btnSubmit" /> 
</form> 

<script type="text/javascript"> 

$(document).ready(function (e) { 

    $("#uploadForm").on('submit',(function(e) { 

    e.preventDefault(); 

    $.ajax({ 

      url: "upload.php", 
      type: "POST", 
      data: new FormData(this), 
      contentType: false, 
      cache: false, 
      processData:false, 

      success: function(data){ 
       $("#targetLayer").html(data); 
      }, 
      error: function(){}    
     }); 

    })); 

}); 

</script> 

upload.php로 (나는 또한이 스크립트를이 문제에 직면하고 생성 된)

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 

if(isset($_FILES["userImage"]["type"])) 
{ 
    $validextensions = array("jpeg", "jpg", "png"); 
    $temporary = explode(".", $_FILES["userImage"]["name"]); 
    $file_extension = end($temporary); 

    $file_type = $_FILES["userImage"]["type"]; 

    if ((($file_type == "image/png") || ($file_type == "image/jpg") || ($file_type == "image/jpeg") 
    ) /*&& ($_FILES["file"]["size"] < 100000)*/ //Approx. 100kb files can be uploaded. 
    && in_array($file_extension, $validextensions)) 
    { 
     if ($_FILES["userImage"]["error"] > 0) 
     { 
      echo "Return Code: " . $_FILES["userImage"]["error"] . "<br/><br/>"; 
     } 
     else 
     { 
      if (file_exists("uploads/" . $_FILES["userImage"]["name"] . '-'.time())) 
      { 
       echo $_FILES["userImage"]["name"] . time() ." <span id='invalid'><b>already exists.</b></span> "; 
      } 
      else 
      { 
       $sourcePath = $_FILES['userImage']['tmp_name']; // Storing source path of the file in a variable 
       $targetPath = "uploads/".$_FILES['userImage']['name'].'-'.time(); // Target path where file is to be stored 

       //check the writable permissions 

       /*if (is_writeable('uploads/' . $_FILES['userImage']['name'])) { 
        die("Cannot write to destination file"); 
       }*/ 

       if(move_uploaded_file($sourcePath,$targetPath)) { 

        echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>"; 
        echo "<br/><b>File Name:</b> " . $_FILES["userImage"]["name"] . "<br>"; 
        echo "<b>Type:</b> " . $_FILES["userImage"]["type"] . "<br>"; 
        echo "<b>Size:</b> " . ($_FILES["userImage"]["size"]/1024) . " kB<br>"; 
        echo "<b>Temp file:</b> " . $_FILES["userImage"]["tmp_name"] . "<br>"; 

       } else { 

        echo "<pre>"; print_r($_FILES['file']['error']); echo "</pre>"; 
       } 
      } 
     } 
    } 
    else 
    { 
    echo "<span id='invalid'>***Invalid file Size or Type***<span>"; 
    } 
} 
?> 

* 동일한 수준 또는 변경에 폴더를 업로드 만들기 업로드 경로에 쓰기 권한을 부여해야합니다.

이 스크립트는 데이터와 파일 모두에서 작동합니다. 게시물 데이터의 경우 $ _POST [ 'post_input']을 사용해야합니다.

이 스크립트를 실행 해보고 도움이되기를 바랍니다.

+0

이것은 내 요구에 완벽하게 작동합니다. 나는 $ file_extension = end ($ temporary) 만 변경했다. ~ $ file_extension = strtolower (끝 ($ 임시)); –

1

$_FILES이 아닌 데이터 파일을 당신이 포스트를 사용하여 데이터를 전송하는 등의 $_POST

0

흠. 큰 파일을 업로드하려고하십니까? 왜냐하면 나는 $ _FILES로 주위를 어지럽 혔기 때문에 20MB보다 큰 파일을 업로드하는 것은 성공하기가 어려웠습니다. 최대 IIS 업로드시 최대 파일을 전송하여 큰 파일을 전송할 수있었습니다. IIS를 망치지 않고 업로드 할 수있는 것은 정상적인 이미지뿐이었습니다.

임시 파일을 사용자가 제공 한 위치에 넣어야하므로 코드가 잘못되었습니다. 정확히 업로드하려고하십니까? 귀하의 코드에서 사용중인 "업로드"폴더가 존재합니까? 그 폴더 doesnt 존재하는 경우 아무런 파일을 이동 못해