更改文件名 Laravel 4

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17282507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:01:23  来源:igfitidea点击:

Change file name Laravel 4

phplaravellaravel-4

提问by Vuk Stankovi?

How can I change name of uploaded file in Laravel 4. So far I have been doing it like this:

如何在 Laravel 4 中更改上传文件的名称。到目前为止,我一直这样做:

$file = Input::file('file'); 
$destinationPath = 'public/downloads/';
if (!file_exists($destinationPath)) {
    mkdir("./".$destinationPath, 0777, true);
}
$filename = $file->getClientOriginalName();

But if I have 2 files with the same name I guess it gets rewritten, so I would like to have something like (2)added at the end of the second file name or to change the file name completely

但是如果我有 2 个同名的文件,我想它会被重写,所以我想(2)在第二个文件名的末尾添加类似的东西或者完全改变文件名

回答by Amal Murali

The first step is to check if the file exists. If it doesn't, extract the filename and extension with pathinfo()and then rename it with the following code:

第一步是检查文件是否存在。如果没有,请提取文件名和扩展名,pathinfo()然后使用以下代码重命名:

$img_name = strtolower(pathinfo($image_name, PATHINFO_FILENAME));
$img_ext =  strtolower(pathinfo($image_name, PATHINFO_EXTENSION));

$filecounter = 1; 

while (file_exists($destinationPath)) {
    $img_duplicate = $img_name . '_' . ++$filecounter . '.'. $img_ext;
    $destinationPath = $destinationPath . $img_duplicate;  
}

The loop will continue renaming files as file_1, file_2etc. as long as the condition file_exists($destinationPath)returns true.

只要条件返回真file_1,循环就会继续将文件重命名为file_2file_exists($destinationPath)

回答by Alejandro Silva

I know this question is closed, but this is a way to check if a filename is already taken, so the original file is not overwriten:

我知道这个问题已经结束,但这是一种检查文件名是否已被占用的方法,因此原始文件不会被覆盖:

(... in the controller: ... )

(...在控制器中:...)

$path = public_path().'\uploads\';
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$original_filename = pathinfo($fileName, PATHINFO_FILENAME);
$new_filename = $this->getNewFileName($original_filename, $extension, $path);
$upload_success = Input::file('file')->move($path, $new_filename);

this function get an "unused" filename:

这个函数得到一个“未使用”的文件名:

public function getNewFileName($filename, $extension, $path){
    $i = 1;
    $new_filename = $filename.'.'.$extension;
    while( File::exists($path.$new_filename) )
        $new_filename = $filename.' ('.$i++.').'.$extension;
    return $new_filename;
}