Multiple files in a folder

Hello, I have a file and a view controller that makes multiple inputs where I can upload files to a folder, but only uploading one file to a folder. I know what the problem is, but I don't know how to fix it or how to do it.

My controller:

public function uploadFile() {
        $filename = '';
            if ($this->request->is('post')) { // checks for the post values
                $uploadData = $this->data['files'];
                //print_r($this->data['files']); die;
                if ( $uploadData['size'] == 0 || $uploadData['error'] !== 0) { // checks for the errors and size of the uploaded file
                    echo "Failide maht kokku ei tohi olla ΓΌle 5MB";
                    return false;
                }
                $filename = basename($uploadData['name']); // gets the base name of the uploaded file
                $uploadFolder = WWW_ROOT. 'files';  // path where the uploaded file has to be saved
                $filename = $filename; // adding time stamp for the uploaded image for uniqueness
                $uploadPath =  $uploadFolder . DS . $filename;
                if( !file_exists($uploadFolder) ){
                    mkdir($uploadFolder); // creates folder if  not found
                }
                if (!move_uploaded_file($uploadData['tmp_name'], $uploadPath)) {
                    return false;
                } 
                echo "Sa sisestasid faili(d): $filename";

            }           
    }

      

My view file:

<?php
    echo $this->Form->create('uploadFile', array( 'type' => 'file'));
?>

    <div class="input_fields_wrap">

        <label for="uploadFilefiles"></label>
        <input type="file" name="data[files]" id="uploadFilefiles">

    </div>

<button type="button" class="add_field_button">+</button> <br><br>

    <form name="frm1" method="post" onsubmit="return greeting()">
        <input type="submit" value="Submit">
    </form>

<?php
echo $this->Html->script('addFile');

      

And this script I am using in the view:

$(document).ready(function() {
    var max_fields      = 3;
    var wrapper         = $(".input_fields_wrap");
    var add_button      = $(".add_field_button");

    var x = 1;
    $(add_button).click(function(e){
        e.preventDefault();
        if(x < max_fields){
            x++;
            $(wrapper).append("<div><input type='file' name='data[files]' id='uploadFilefiles'/><a href='#' class='remove_field'>Kustuta</a></div>");
        }
     });

      $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
            e.preventDefault(); $(this).parent('div').remove(); x--;
        })
});

      

I think the problem is with the input names. If Im making more input then the input names are the same and thanks to that it only uploads one file to the webroot / files folder but I want it all.

Can someone help me or give me some advice. Thank!

+3


source to share


2 answers


Here is someone with almost the same problem as yours: Create multiple upload files dynamically

Try to do the same. I haven't programmed PHP for some time, but I think you should replace data[files]

with data[]

, so it creates a new array element for each field. Now you are giving each field the same name.

Then you can iterate over them in your controller using:



foreach($_FILES['data'] as $file){
  //do stuff with $file
}

      

EDIT 2: As you say, you want to upload files (not db). So I think this should work:

public function uploadFile() {
        $filename = '';
            if ($this->request->is('post')) { // checks for the post values
                $uploadData = $this->data;
                foreach($uploadData as $file){

                if ( $file['size'] == 0 || $file['error'] !== 0) { // checks for the errors and size of the uploaded file
                    echo "Failide maht kokku ei tohi olla ΓΌle 5MB";
                    return false;
                }
                $filename = basename($file['name']); // gets the base name of the uploaded file
                $uploadFolder = WWW_ROOT. 'files';  // path where the uploaded file has to be saved
                $filename = $filename; // adding time stamp for the uploaded image for uniqueness
                $uploadPath =  $uploadFolder . DS . $filename;
                if( !file_exists($uploadFolder) ){
                    mkdir($uploadFolder); // creates folder if  not found
                }
                if (!move_uploaded_file($file['tmp_name'], $file)) {
                    return false;
                } 
                echo "Sa sisestasid faili(d): $filename";

            }       
         }    
    }

      

+1


source


Try this function:

function multi_upload($file_id, $folder="", $types="") {
        $all_types = explode(",",strtolower($types));
        foreach($_FILES[$file_id]['tmp_name'] as $key => $tmp_name ){
            if(!$_FILES[$file_id]['name'][$key]){
                $return[$key]= array('','No file specified');
                continue;
            }
            $file_title = $_FILES[$file_id]['name'][$key];
            $ext_arr = pathinfo($file_title, PATHINFO_EXTENSION);
            $ext = strtolower($ext_arr); //Get the last extension
            //Not really uniqe - but for all practical reasons, it is
            $uniqer = substr(md5(uniqid(rand(),1)),0,5);
            $file_name = $uniqer . '_' . $file_title;//Get Unique Name
            if($types!=''){
                if(in_array($ext,$all_types));
                else {
                    $result = "'".$_FILES[$file_id]['name'][$key]."' is not a valid file."; //Show error if any.
                    $return[$key]= array('',$result);
                    continue;
                }
            }
            //Where the file must be uploaded to
            if($folder) $folder .= '/';//Add a '/' at the end of the folder
            $uploadfile = $folder . $file_name;
            $result = '';
            //Move the file from the stored location to the new location
            if (!move_uploaded_file($_FILES[$file_id]['tmp_name'][$key], $uploadfile)) {
                $result = "Cannot upload the file '".$_FILES[$file_id]['name'][$key]."'"; //Show error if any.
                if(!file_exists($folder)) {
                    $result .= " : Folder don't exist.";
                    } elseif(!is_writable($folder)) {
                    $result .= " : Folder not writable.";
                    } elseif(!is_writable($uploadfile)) {
                    $result .= " : File not writable.";
                }
                $file_name = '';
            } 
            else {
                if(!$_FILES[$file_id]['size']) { //Check if the file is made
                    @unlink($uploadfile);//Delete the Empty file
                    $file_name = '';
                    $result = "Empty file found - please use a valid file."; //Show the error message
                }
                else {
                    @chmod($uploadfile,0777);//Make it universally writable.
                }
            }
            $return[$key]=array($file_name,$result);
        }
        return $return;
    }

      



html: <input type="file" name="data_file[]" id="uploadFilefiles">

Call multi_upload("data_file","upload_to_folder","pdf,jpg,txt,bmp")

0


source







All Articles