如何在mysql数据库中插入带有文件上传器值的多个文本框?

时间:2016-10-08 05:10:44

标签: php jquery mysql sql file-upload

我有多个带文件上传器的文本框但我无法将文件存储在文件夹路径中。我想添加更多字段用于上传并将文件存储在特定文件夹中。

我尝试了一切。我已经附上了我的代码请看。

抱歉我的英语不好。

用于上传的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'];
	  
      $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(){
	var maxField = 10; //Input fields increment limitation
	var addButton = $('.add_button'); //Add button selector
	var wrapper = $('.field_wrapper'); //Input field wrapper
	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 
	var x = 1; //Initial field counter is 1
	$(addButton).click(function(){ //Once add button is clicked
		if(x < maxField){ //Check maximum number of input fields
			x++; //Increment field counter
			$(wrapper).append(fieldHTML); // Add field html
		}
	});
	$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
		e.preventDefault();
		$(this).parent('div').remove(); //Remove field html
		x--; //Decrement field counter
	});
});
</script>
<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="">
        <a href="javascript:void(0);" class="add_button" title="Add field">Add</a>
         <input type="submit" name="submit" value="SUBMIT"/>
         
    </div>
   

</div>
</form>

2 个答案:

答案 0 :(得分: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链接。

答案 1 :(得分:0)

您只需在foreach数组上执行$_FILES循环。这是这个问题的重复,并且多次被问及回答:

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);
            }
    }

要应用于页面(业务逻辑)将类似于:

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;

回报显示类似于此的内容:

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}]