当我存储上传的文件时,我使用Laravel Storage::putFile()
,我喜欢它的自动唯一文件名的便利性以及它如何处理文件扩展名。
现在我想从远程服务器(file_get_contents($url)
)获取一个文件,并像上传文件那样存储它,但我在文档中找不到任何相同的方法。
在put
方法的https://laravel.com/docs/5.5/filesystem#storing-files中,您必须指定文件名。
答案 0 :(得分:5)
$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));
答案 1 :(得分:2)
如果您有UploadedFile
个实例,也可以使用$file->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
答案 2 :(得分:1)
要确保文件名是唯一的并且要获取文件网址的扩展名,您可以这样做:
$ext = pathinfo($url, PATHINFO_EXTENSION);
$filename = bcrypt($url).time().'.'.$ext;