doudi8519 2016-10-08 05:10 采纳率: 100%
浏览 52
已采纳

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

i have multiple textbox with file uploader but i can't able to store the file in folder path. i want to add more fields for upload and store the files in the specific folder.

I tried everything. i have attached my code with this please look.

Sorry for my bad english.

PHP code for upload:

<?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>

</div>
  • 写回答

2条回答 默认 最新

  • dongling5411 2016-10-08 08:04
    关注

    You just do a foreach loop over the $_FILES array. This is a duplicate of this question and has been asked and answered many times over:

    Multiple file upload in php

    That being said, since it's been answered already and so I don't just regurgitate what's already out there, I will add a bit more to this answer. In this day and age, you can't just simply upload a file. Likely you will want to keep records of it in a database or show some stats on the view after the page reloads. To do that you need to use a class/method system (in my opinion) where you can actually do the upload but also get useful information back. A framework would take care of all this for you (and more!), but for the sake of this answer, here is a simple example, maybe it will give you ideas:

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

    To apply to the page (the business logic) would be something like:

    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;
    

    The return shows something similar to this:

    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}]      
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料