Laravel 上传图片并生成随机 ID 作为名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48441149/
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
Laravel Upload Image and Generate Random ID as name
提问by DanTheDJ1
Whats the best way to generate and random ID number for every image where i want upload in Laravel 5?
为我想在 Laravel 5 中上传的每个图像生成和随机 ID 号的最佳方法是什么?
My Upload:
我的上传:
<input type="file" id="mypicture" name="mypicture">
Controller:
控制器:
public function MyPicture(Request $request){
$user = Auth::user();
$user->mypicture= $request->mypicture;
$user->save();
return redirect()->back();
}
Thats the way i do it always for other things:
这就是我总是为其他事情做的方式:
->uniqueid = 'VA'.str_random(28);
how can i add it to my Controller for image name? And how can i use only alphabetic character not numbers? Or i must change my DB Table.
我如何将它添加到我的控制器以获取图像名称?我怎样才能只使用字母字符而不使用数字?或者我必须更改我的数据库表。
Thanks
谢谢
回答by Gaurav Dave
Try this:
尝试这个:
public function MyPicture(Request $request){
$user = Auth::user();
$user->mypicture = date('mdYHis') . uniqid() . $request->mypicture;
$user->save();
return redirect()->back();
}
You can use Date (Y-m-d H:i:s) and uniqid()
to generate unique name every file.
您可以使用 Date (Ymd H:i:s) 并uniqid()
为每个文件生成唯一名称。
回答by DanTheDJ1
Laravel has an inbuilt method for this, using their File facade.
Laravel 有一个内置的方法,使用它们的 File 外观。
From laravel docs:
来自 Laravel 文档:
$path = $request->file('avatar')->store('avatars');
return $path;
By default, the store method will generate a unique ID to serve as the file name. The path to the file will be returned by the store method so you can store the path, including the generated file name, in your database.
默认情况下,store 方法会生成一个唯一的 ID 作为文件名。文件的路径将由 store 方法返回,因此您可以在数据库中存储路径,包括生成的文件名。
回答by Sohel0415
回答by Alexey Mezenin
Do the same here:
在这里做同样的事情:
$user = Auth::user();
$user->mypicture = $request->mypicture;
$user->filename = str_random(28);
$user->save();
$request->mypicture->storeAs('images', $user->filename);
If you want to use only letters, use one of the existing solutions.
如果只想使用字母,请使用现有解决方案之一。