我为同一个文件得到不同的随机值

I get different random values for the same file

我正在尝试将照片存储在数据库中,我使用以下方式生成一个随机文件名并将其存储在数据库中。

 $path = $request->file('profile_photo')->store('public/profiles');
        $profile = ltrim($path,"public/profiles/");

但是,有时我在 数据库

我的文件夹

我正在使用 laravel 6。

ltrim()rtrim()trim() 按字符掩码删除,而不是完整字符串。

$profile = ltrim($path,"public/profiles/");

表示去掉所有"p"、"u"、"b"、"l"、"i"、"c"、“/”等. 从 $path.

的左侧开始

如果你想得到没有路径的文件名,你可以使用basename()函数。

$profile = basename($path);

好的,看看这个src/Illuminate/Http/UploadedFile.php

/**
 * Store the uploaded file on a filesystem disk.
 *
 * @param  string  $path
 * @param  array|string  $options
 * @return string|false
 */
public function store($path, $options = [])
{
    return $this->storeAs($path, $this->hashName(), $this->parseOptions($options));
}
/**
 * Store the uploaded file on a filesystem disk.
 *
 * @param  string  $path
 * @param  string  $name
 * @param  array|string  $options
 * @return string|false
 */
public function storeAs($path, $name, $options = [])
{
    $options = $this->parseOptions($options);

    $disk = Arr::pull($options, 'disk');

    return Container::getInstance()->make(FilesystemFactory::class)->disk($disk)->putFileAs(
        $path, $this, $name, $options
    );
}

你可以这样做来摆脱碰撞和混乱

// cache the file
$file = $request->file('profile_photo');

// generate a new filename. getClientOriginalExtension() for the file extension
$filename = 'profile-photo-' . time() . '.' . $file->getClientOriginalExtension();

// save to public/photos as the new $filename
$path = $file->store('public/photos', $filename);

dd($path); // Check if you get the correct file path or not