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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:41:44  来源:igfitidea点击:

Laravel generate a unique ID using Storage::put

laravellaravel-5

提问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 putmethod, you have to specify the file name.

https://laravel.com/docs/5.5/filesystem#storing-filesput方法中,必须指定文件名。

回答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 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;