繁体   English   中英

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

[英]how to insert multiple text box with file uploader values in mysql database?

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

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

对不起,我的英语不好。

用于上传的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> 

请使用以下代码上传多个文件:

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

请确保您已授予图像文件夹的权限。 有关更多详细信息,请参阅链接。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM