调试Text :: uuid()与实际上传的文件路径Cakephp 3之间的不一致

时间:2016-03-22 20:19:19

标签: php cakephp file-upload cakephp-3.0 uuid

我目前正在尝试在Cakephp 3项目中进行文件上传。我的上传组件中有以下功能,可以将文件(通过$ this-> request-> data提供输入)保存到webroot / img / uploads中:

public function send( $data )
{
    if ( !empty( $data ) ) {
        if ( count( $data ) > $this->maxFiles ) {
            throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
        }
        $fileNames = [];
        $count = 0;
        foreach ($data as $file) {
            $filename = $file['name'];
            $file_tmp_name = $file['tmp_name'];
            $dir = WWW_ROOT.'img'.DS.'uploads';
            $allowed = ['png', 'jpg', 'jpeg'];
            if ( !in_array( substr( strrchr( $filename , '.') , 1 ) , $allowed) ) {
                // Iterate through extension to sum up what types of files are allowed to upload
                $output = "Error Processing Request. It is only allowed to upload files with the following extensions: ";
                foreach($this->allowed as $extension){ $output .= $extension . ' '; }
                throw new InternalErrorException($output, 1);   
            }elseif( is_uploaded_file( $file_tmp_name ) ){
                debug(Text::uuid().'-'.$filename);
                debug($file_tmp_name);
                move_uploaded_file($file_tmp_name, $dir.DS.Text::uuid().'-'.$filename);
            }
        }
    }
}

此函数确实将文件保存到指定的文件夹,但文件名不同于调试Text :: uuid()时的文件名。' - '。$ filename。

调试输出:

f5b0ca4f-cb73-4382-b1ca-0eee232ab17a-phinx.png


webroot / img / uploads文件夹中的文件名:

4a635fa6-98ea-461e-a98d-0f6ac34c65e7-phinx.png

我的问题是:有没有人知道如何获取上传到webroot / img / uploads文件夹的文件名?我想这样做的原因是,我想将这些路径保存到数据库中。

1 个答案:

答案 0 :(得分:0)

感谢gmponos,将Text :: uuid()的id存储到一个单独的变量中非常重要。这对我有用。

public function send( $data )
{
    if ( !empty( $data ) ) {
        if ( count( $data ) > $this->maxFiles ) {
            throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
        }
        $fileNames = [];
        $count = 0;
        foreach ($data as $file) {
            $filename = $file['name'];
            $file_tmp_name = $file['tmp_name'];
            $dir = WWW_ROOT.'img'.DS.'uploads';
            $allowed = ['png', 'jpg', 'jpeg'];
            if ( !in_array( substr( strrchr( $filename , '.') , 1 ) , $allowed) ) {
                // Iterate through extension to sum up what types of files are allowed to upload
                $output = "Error Processing Request. It is only allowed to upload files with the following extensions: ";
                foreach($this->allowed as $extension){ $output .= $extension . ' '; }
                throw new InternalErrorException($output, 1);   
            }elseif( is_uploaded_file( $file_tmp_name ) ){
                $uuid = Text::uuid();
                move_uploaded_file($file_tmp_name, $dir.DS.$uuid.'-'.$filename);
            }
        }
    }
}