2016-10-08 6 views
0

ファイルアップローダーで複数のテキストボックスがありますが、フォルダパスにファイルを保存できません。私はアップロードのためのフィールドを追加し、特定のフォルダにファイルを保存したい。mysqlデータベースにファイルアップローダの値を含む複数のテキストボックスを挿入するには?

私はすべてを試しました。私はこれを見てください私のコードを添付している。

私の悪い英語のために申し訳ありません。アップロード用

PHPコード:

<?php if(isset($_FILES['attach'])){ 
 
     $errors= array(); 
 
     $file_name = $_FILES['attach']['name']; 
 
     $file_size =$_FILES['attach']['size']; 
 
     $file_tmp =$_FILES['attach']['tmp_name']; 
 
     $file_type=$_FILES['attach']['type']; 
 
\t 
 
     $file_ext=strtolower(end(explode('.',$_FILES['attach']['name']))); 
 
     
 
     $extensions= array("jpeg","jpg","png"); 
 
     
 
     if(in_array($file_ext,$extensions)=== false){ 
 
     $errors[]="extension not allowed, please choose a JPEG or PNG file."; 
 
     } 
 
     
 
     if($file_size < 2097152){ 
 
     $errors[]='File size must be excately 2 MB'; 
 
     } 
 
     
 
     if(empty($errors)==true){ 
 
     move_uploaded_file($file_tmp,"images/".$file_name); 
 
     echo "Success"; 
 
     }else{ 
 
     print_r($errors); 
 
     } 
 
    } 
 
?>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type = "text/javascript"></script> 
 

 

 
<script type="text/javascript"> 
 

 

 
$(document).ready(function(){ 
 
\t var maxField = 10; //Input fields increment limitation 
 
\t var addButton = $('.add_button'); //Add button selector 
 
\t var wrapper = $('.field_wrapper'); //Input field wrapper 
 
\t var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><input type="text" name="hint[]" value=""> <input type="file" name="attach[]" value=""><a href="javascript:void(0);" class="remove_button" title="Remove field"><img src="remove-icon.png" alt="Remove"/></a></div>'; //New input field html 
 
\t var x = 1; //Initial field counter is 1 
 
\t $(addButton).click(function(){ //Once add button is clicked 
 
\t \t if(x < maxField){ //Check maximum number of input fields 
 
\t \t \t x++; //Increment field counter 
 
\t \t \t $(wrapper).append(fieldHTML); // Add field html 
 
\t \t } 
 
\t }); 
 
\t $(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked 
 
\t \t e.preventDefault(); 
 
\t \t $(this).parent('div').remove(); //Remove field html 
 
\t \t x--; //Decrement field counter 
 
\t }); 
 
}); 
 
</script>
<form name="" action="" method="post" enctype="multipart/form-data"> 
 
<div class="field_wrapper" id="qus_box"> 
 
\t <div> 
 
    
 
    \t <input type="text" name="field_name[]" value=""/> 
 
     <input type="text" name="hint[]" value=""> 
 
     <input type="file" name="attach[]" value=""> 
 
     <a href="javascript:void(0);" class="add_button" title="Add field">Add</a> 
 
     <input type="submit" name="submit" value="SUBMIT"/> 
 
      
 
    </div> 
 
    
 

 
</div> 
 
</form>

答えて

0

配列の上にforeachループを実行するだけです。それはすでに回答されていますので、私はちょうどそこにすでに何逆流しないので、私は意志、

Multiple file upload in php

それは言われている:これは、この質問の重複であると何度も尋ねたと回答されていますこの答えにもう少し追加してください。この日や年齢では、単にファイルをアップロードするだけではありません。おそらく、データベースにレコードを保存したり、ページのリロード後にビューにいくつかの統計情報を表示したりすることができます。これを行うには、あなたが実際にアップロードを行うことができるクラス/メソッドシステム(私の意見では)を使う必要がありますが、役に立つ情報を取り戻す必要があります。 フレームワークがあなたのためにこのすべての世話をする(!そしてもっと)が、この答えのために、ここでは簡単な例であるだろう、多分それはあなたのアイデアを与えるだろう。

class Files 
    { 
     private $filesArr, 
       $destination, 
       $errors, 
       $success, 
       $full_path; 
     /* 
     ** @description This will point the image uploads to a folder 
     ** @param $dir [string] This is the directory where files will save 
     ** @param $make [bool] This will instruct the method to make or not 
     ** make a folder if not exists 
     */ 
     public function setDest($dir,$make = true) 
      { 
       if(!is_dir($dir)) { 
        if(!$make || ($make && !mkdir($dir,0755,true))) 
         throw new Exception('Directory does not exist'); 
       } 
       $this->destination = $dir; 
       return $this; 
      } 
     /* 
     ** @description This will upload the files and keep some records 
     ** for reference after the fact 
     */ 
     public function saveFiles() 
      { 
       if(empty($this->filesArr)){ 
        throw new Exception('No files to upload.'); 
        return false; 
       } 
       foreach($this->filesArr as $file) { 
        $filename = $file['name'].'.'.$file['ext']; 
        if(!move_uploaded_file($file['tmp_name'],$this->destination.'/'.$filename)) 
         throw new Exception('Could not save file "'.htmlspecialchars($filename).'" to folder.'); 
        else { 
         $this->full_path[] = $this->destination.'/'.$filename; 
         $this->success[] = $filename; 
        } 
       } 
      } 
     /* 
     ** @description This organized the files array and allows you to 
     ** set different listeners 
     */ 
     public function organize($key) 
      { 
       foreach($_FILES[$key]['name'] as $num => $val) { 
        $ext = $this->getExt($val); 
        $size = $_FILES[$key]['size'][$num]; 
        $name = pathinfo($val,PATHINFO_FILENAME); 

        if($_FILES[$key]['error'][$num] != 0) { 
         $this->errors[] = 'An error occurred: '.htmlspecialchars($name); 
         continue; 
        } 
        elseif(!$this->typeAllowed($ext)) { 
         $this->errors[] = 'File type not allowed ('.htmlspecialchars($ext).') :'.htmlspecialchars($name); 
         continue; 
        } 
        elseif(!$this->sizeAllowed($size)){ 
         $this->errors[] = 'File too big: '.htmlspecialchars($name); 
         continue; 
        } 

        $this->filesArr[$num]['name']  = $name; 
        $this->filesArr[$num]['ext']  = $ext; 
        $this->filesArr[$num]['tmp_name'] = $_FILES[$key]['tmp_name'][$num]; 
        $this->filesArr[$num]['size']  = $size; 
        $this->filesArr[$num]['tmp_name'] = $_FILES[$key]['tmp_name'][$num]; 
        # I would put a path. I would remove directories outside 
        # of the root from the destination path. This way you 
        # can move a website to different web hosts and the 
        # path will still be good because it will be relative to 
        # the site root, not the server root. This is only important 
        # if you plan to store the path in a database... 
        $this->filesArr[$num]['full_path'] = $this->destination.'/'.$name.'.'.$ext; 
       } 

       return $this; 
      } 
     /* 
     ** @description This just gives a summary of the actions taken in 
     ** the event 
     */ 
     public function getStats() 
      { 
       $extsCnt = array(); 
       $fileSum = 0; 
       if(!empty($this->filesArr)) { 
        foreach($this->filesArr as $files) { 
         $store['ext'][]  = $files['ext']; 
         $store['size'][] = $files['size']; 
        } 

        if(!empty($store)){ 
         $extsCnt = array_count_values($store['ext']); 
         $fileSum = array_sum($store['size']); 
        } 
       } 
       return array(
        'success'=>(!empty($this->filesArr))? count($this->filesArr):0, 
        'errors'=>(!empty($this->errors))? count($this->errors):0, 
        'total_uploaded'=>$fileSum, 
        'extension_count'=>$extsCnt 
       ); 
      } 

     public function toJson() 
      { 
       return json_encode($this->getFiles()); 
      } 

     public function getFiles() 
      { 
       return $this->filesArr; 
      } 

     public function getErrors() 
      { 
       return $this->errors; 
      } 

     public function getSuccess() 
      { 
       return $this->success; 
      } 

     public function getPaths() 
      { 
       return $this->full_path; 
      } 
     # This method is a little weak. It needs to be more flexible 
     # Should be able to add/remove file types 
     public function typeAllowed($ext) 
      { 
       return in_array($ext,array("jpeg","jpg","png",'sql')); 
      } 

     public function getExt($filename) 
      { 
       return strtolower(pathinfo($filename,PATHINFO_EXTENSION)); 
      } 

     public function sizeAllowed($size,$max = 2097152) 
      { 
       return ($size <= $max); 
      } 
    } 

に適用するには

File type not allowed (pdf) : Filename1 

Uploaded: Filename2.jpg 
Uploaded: Filename3.png 
Uploaded: Filename4.png 

Array 
(
    [0] => Array 
     (
      [name] => Filename2 
      [ext] => jpg 
      [tmp_name] => /datatmp/phpwDpP27 
      [size] => 17251 
      [full_path] => root/path/httpdocs/file/to/save/here/Filename2.jpg 
     ) 

    [1] => Array 
     (
      [name] => Filename3 
      [ext] => png 
      [tmp_name] => /datatmp/phpDXlSmH 
      [size] => 22636 
      [full_path] => root/path/httpdocs/file/to/save/here/Filename3.png 
     ) 

    [2] => Array 
     (
      [name] => Filename3 
      [ext] => png 
      [tmp_name] => /datatmp/phpSfE2Hg 
      [size] => 398811 
      [full_path] => root/path/httpdocs/file/to/save/here/Filename3.png 
     ) 

) 

     Array 
(
    [success] => 3 
    [errors] => 1 
    [total_uploaded] => 438698 
    [extension_count] => Array 
     (
      [jpg] => 1 
      [png] => 2 
     ) 

) 

    [{"name":"Filename2","ext":"jpg","tmp_name":"\/datatmp\/phpwDpP27","size":17251},{"name":"Filename3","ext":"png","tmp_name":"\/datatmp\/phpDXlSmH","size":22636},{"name":"Filename4","ext":"png","tmp_name":"\/datatmp\/phpSfE2Hg","size":398811}]  
:リターンはこれに似たものを示して

if(isset($_FILES['attach'])){ 
    try { 
     # Create our instance 
     $fileManager = new Files(); 
     # Set where we want to save files to 
     $fileManager 
      ->setDest(__DIR__.'/file/to/save/here') 
      # Process what name from the form 
      ->organize('attach') 
      # Do the upload 
      ->saveFiles(); 
    } 
    # Catch any errors thrown 
    catch(Exception $e) { 
     #You would probably want to display this in the view 
     # so output buffer works here 
     ob_start(); 
?> 
<script> 
alert('<?php echo $e->getMessage(); ?>'); 
</script> 
<?php 
     $catch = ob_get_contents(); 
     ob_end_clean(); 
    } 
} 

# Here are some helpful data returns for DB storage or page view 
if(isset($fileManager)) { 
    # Show errors 
    echo implode('<br />',$fileManager->getErrors()).'<br />'; 
    # Show successful uploads 
    if(!empty($fileManager->getSuccess())) 
     echo 'Uploaded: '.implode('<br />Uploaded: ',$fileManager->getSuccess()); 
    # Just some information that can be passed to other classes 
    print_r($fileManager->getFiles()); 
    print_r($fileManager->getStats()); 
    print_r($fileManager->toJson()); 
} 

# Show alert in the view somewhere 
if(isset($catch)) 
    echo $catch; 

:ページ(ビジネスロジック)は、のようなものになるでしょう

0

複数のファイルのアップロードのために、このコードを使用してください:

<form name="" action="" method="post" enctype="multipart/form-data"> 
    <div class="field_wrapper" id="qus_box"> 
    <div>  
<input type="text" name="field_name[]" value=""/> 
<input type="text" name="hint[]" value=""> 
<input type="file" name="attach[]" value="" multiple="multiple"> 
<a href="javascript:void(0);" class="add_button" title="Add field">Add</a> 
<input type="submit" name="submit" value="SUBMIT"/>   
    </div> 
    </div> 
</form> 

<?php 

if(isset($_FILES['attach'])){ 
$errors= array(); 
    $file_name = $_FILES['attach']['name']; 
    $file_size =$_FILES['attach']['size']; 
    $file_tmp =$_FILES['attach']['tmp_name']; 
    $file_type=$_FILES['attach']['type']; 
    $file_error = $_FILES['attach']['error']; 
    $extensions= array("jpeg","jpg","png");  

    foreach ($file_name as $f => $name) { 
$file_ext=strtolower(end(explode('.',$name))); 

if(in_array($file_ext,$extensions)=== false){ 
$errors[]="extension not allowed, please choose a JPEG or PNG file."; 
} 

if($file_size < 2097152){ 
    $errors[]='File size must be excately 2 MB'; 
} 

if(empty($errors)==true){ 
move_uploaded_file($file_tmp[$f],"images/".$file_name[$f]); 
echo "Success"; 
    }else{ 
     print_r($errors); 
    } 
} 
?> 

画像フォルダへのアクセス許可を確認してください。 詳細についてはthisリンクを参照してください。

関連する問題