多个文件到文件夹中

时间:2015-01-08 08:13:32

标签: javascript php html cakephp

您好我有一个视图文件和控制器,是什么使多个输入我可以将文件上传到文件夹,但它只上传一个文件到文件夹。我知道什么是问题,但我不知道如何解决这个或如何做到这一点。

我的控制器:

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";

            }           
    }

我的观看文件:

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

这个脚本我在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--;
        })
});

我认为,问题在于输入名称。如果我做了更多输入,那么输入名称是相同的,并且由于这个,它只将一个文件上传到webroot / files文件夹,但我想要这些。

任何人都可以帮助我或给我一些提示。 谢谢!

2 个答案:

答案 0 :(得分:1)

以下是与您有完全相同问题的人: Create multiple Upload File dynamically

尝试做同样的事情。我没有编程PHP很长一段时间,但我想你应该将data[files]替换为data[],因此它会为每个字段创建一个新的数组项。现在,您为每个字段指定了相同的名称。

然后,您可以使用以下命令在控制器中循环它们:

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

编辑2: 正如您所说,您希望上传文件(而不是数据库)。所以我想这应该有用:

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 :(得分:0)

尝试此功能:

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

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

打电话