在 laravel 中上传时如何为图片创建唯一的名称?

How to make unique name for image during upload in laravel?

我正在使用 laravel 5.5 并上传图片。 我的代码以错误的方式生成名称。

 $image_icon = $request->file('image_icon');
 $data['image'] = $image_icon->getClientOriginalName().'.'.time();
 $destinationPath = public_path('/images');
 $image_icon->move($destinationPath, $data['image']);

图像的输出名称如下:heart.png.1544074437

名字应该是:heart1544074437.png

使用 pathinfo 函数试试这个

提取文件名..

$fileName = pathinfo($image_icon->getClientOriginalName(), PATHINFO_FILENAME);

提取扩展

$extension = pathinfo($image_icon->getClientOriginalName(), PATHINFO_EXTENSION);

创建新文件名。

$fullFileName = $fileName."-".time().$image_icon->getClientOriginalExtension();

有关详细信息,请参阅此 question

使用pathinfo()

pathinfo — Returns information about a file path

path The path to be parsed.

options If present, specifies a specific element to be returned; one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.

If options is not specified, returns all available elements.

$image_icon = $request->file('image_icon')->getClientOriginalName();

$filename = pathinfo($image_icon, PATHINFO_FILENAME);
$extension = pathinfo($image_icon, PATHINFO_EXTENSION);
$data['image'] = $filename.time().'.'.$extension;

您可以这样做:

$image = explode(".", $image_icon);
$image_name = $image[0];
$image_extension = array_slice($image , -1, 1);

$data['image'] = $image_name.time().'.'.$image_extension[0];

我希望这对您的问题有帮助和简单的解决方案。 谢谢

试试这个

 $imgName = md5(str_random(30).time().'_'.$request->file('image_icon')).'.'.$request->file('image_icon')->getClientOriginalExtension();

以上代码需要小的改进如下:

$image_icon = $request->file('image_icon');

$fileName = pathinfo($image_icon->getClientOriginalName(), PATHINFO_FILENAME);

$extension = pathinfo($image_icon->getClientOriginalName(), PATHINFO_EXTENSION);

$data['image'] = $image_icon->getClientOriginalName().time().'.'.$extension;

我没有测试过这段代码,但它应该可以工作。

您还可以使用 laravel 开箱即用的上传解决方案:

$request->photo->store('images');

更多信息请查看这里:https://laravel.com/docs/5.5/requests#files

下面的代码对我来说工作正常。

// extract file name ..

        $fileName = pathinfo($fileupload_dt->getClientOriginalName(), PATHINFO_FILENAME);
        
        // extract extenstion

        $extension = pathinfo($fileupload_dt->getClientOriginalName(), PATHINFO_EXTENSION);
        
        // create new file name.

        $imageName = $fileName."-".time().".".$fileupload_dt->getClientOriginalExtension();

        $uploadPath = 'public/ArchiveImg/img';
        $fileupload_dt->move($uploadPath,$imageName);
        $imageUrl = $uploadPath.$imageName;