Laravel 使用 Storage::put 生成唯一 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46359493/
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 generate a unique ID using Storage::put
提问by Webinan
I use Laravel Storage::putFile()
when I store uploaded files and I like the convenience of it's automatic unique file name and how it takes care of file extension.
我Storage::putFile()
在存储上传的文件时使用 Laravel ,我喜欢它的自动唯一文件名的便利性以及它如何处理文件扩展名。
Now I want to get a file from a remote server (file_get_contents($url)
) and store it like I did for uploaded files, but I don't find any equal method in the docs.
现在我想从远程服务器 ( file_get_contents($url)
)获取一个文件并像我上传文件一样存储它,但我在文档中找不到任何相同的方法。
In https://laravel.com/docs/5.5/filesystem#storing-filesin the put
method, you have to specify the file name.
在https://laravel.com/docs/5.5/filesystem#storing-files的put
方法中,必须指定文件名。
回答by BugraDayi
$filename = uniqid().File::extension($file->getClientOriginalName());
//uniqid() is php function to generate uniqid but you can use time() etc.
$path = "Files/Images/"
Storage::disk('local')->put($path.$filename,file_get_contents($file));
回答by Eduardo Stuart
If you have an UploadedFile
instance you can also use $file->hashName()
如果你有一个UploadedFile
实例,你也可以使用$file->hashName()
https://laravel.com/api/5.5/Illuminate/Http/UploadedFile.html#method_hashName
https://laravel.com/api/5.5/Illuminate/Http/UploadedFile.html#method_hashName
https://github.com/laravel/framework/blob/5.5/src/Illuminate/Http/FileHelpers.php#L52
https://github.com/laravel/framework/blob/5.5/src/Illuminate/Http/FileHelpers.php#L52
回答by Thibault Dumas
To be sure the filename is unique and to get the extension of your file url, you can do like this :
要确保文件名是唯一的并获取文件 url 的扩展名,您可以这样做:
$ext = pathinfo($url, PATHINFO_EXTENSION);
$filename = bcrypt($url).time().'.'.$ext;