php 在laravel中上载文件名时自动递增文件名

lx0bsm1f  于 2022-12-10  发布在  PHP
关注(0)|答案(4)|浏览(165)

我写了一个控制器上传文件到一个目录。我想如果一个文件已经存在于该目录中,在移动之前,文件名要通过增加一个单位从最后一个类似的存在的文件名改变,像这样:

test.jpg
test(1).jpg
test(2).jpg

这是我的控制器的主体

$fileName = $file->getClientOriginalName();
$fileExt  = $file->getClientOriginalExtension();

$destinationFolder = public_path('upload/userfiles/');
$num   = 1;

$newName = $fileName;

while (file_exists($destinationFolder . $newName )) {
    $newName = $fileName. '(' . $num . ')';
    $num ++;
}

$file->move($destinationFolder, $newName . '.' . $fileExt);

但这不能正常工作,创建的文件名如下:

test.jpg
test(1).jpg
test(1)(2).jpg
dfty9e19

dfty9e191#

你问题是:
$newName = $fileName;一开始是test.jpg,然后添加($num++),使其成为test(1).jpg
下一次它仍然是test(1).jpg,并且您附加了($num++),那么它将变成test(1)(2).jpg
就是这样

dw1jzc5e

dw1jzc5e2#

这将起作用:

$fileName = $file->getClientOriginalName();
$fileExt  = $file->getClientOriginalExtension();

$destinationFolder = public_path('upload/userfiles/');
$num   = 1;

$newName = $fileName;

$appendNum = false;
while (file_exists($destinationFolder . $newName )) {
    $appendNum = true;
    $num ++;
}
if ($appendNum) $newName = $fileName. '(' . $num . ')';
$file->move($destinationFolder, $newName . '.' . $fileExt);
vmpqdwk3

vmpqdwk33#

这对我很有效:

$current_name   = $file->getClientOriginalName();
        $extension      = $file->getClientOriginalExtension();
        $only_name      = explode('.', $current_name)[0];
        $new_name       = $current_name;

        $destination    = Storage::disk($link_directory)->path($folder);
        $all_files      = Storage::disk($link_directory)->listContents($folder);
        $searchword     = $only_name;
        $matches        = array_filter($all_files, function($var) use ($searchword) { 
            if(strpos($var['filename'], $searchword) !== FALSE) {  
                return $var;
            }
        });

        if( is_array($matches) ){
            $new_name = $only_name. '_' . count($matches).'.'.$extension;
        }

        $filename       = Storage::disk($link_directory)->putFileAs($folder, $file, $new_name);
lndjwyie

lndjwyie4#

我创建了一个简单的helper函数,用于生成文件名:

if (!function_exists('generateFilename')) {
    /**
     * Generate filename
     *
     * @param string $disk
     * @param string $path
     * @param UploadedFile $file
     * @param integer $count
     * @return string $filename
     */
    function generateFilename(string $disk, string $path, UploadedFile $file, int $count = 0)
    {
        $extension = $file->getClientOriginalExtension();
        $filename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) . ($count == 0 ? "." . $extension :  "-{$count}." . $extension);
        $filePath = Str::of($path)->finish(DIRECTORY_SEPARATOR)->finish($filename)->toString();
        if (Storage::disk($disk)->exists($filePath)) {
            $count++;
            return generateFilename($disk, $path, $file, $count);
        }

        return $filename;
    }
}

相关问题