我在存储上传文件时使用Laravel的Storage :: putFile()
,我喜欢它自动为文件命名并处理文件扩展名的便利性。
现在我想像上传文件一样从远程服务器获取文件(file_get_contents($url)
),但是我在文档中找不到相应的方法。
在https://laravel.com/docs/5.5/filesystem#storing-files的put
方法中,您需要指定文件名。
我在存储上传文件时使用Laravel的Storage :: putFile()
,我喜欢它自动为文件命名并处理文件扩展名的便利性。
现在我想像上传文件一样从远程服务器获取文件(file_get_contents($url)
),但是我在文档中找不到相应的方法。
在https://laravel.com/docs/5.5/filesystem#storing-files的put
方法中,您需要指定文件名。
$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));
file_get_contents
对我起作用了,谢谢。 - Maha DevUploadedFile
实例,您也可以使用$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
如果有人正在寻找默认的Laravel唯一文件名生成器,在上传新文件时,Laravel在幕后使用Str::random(40)
来生成唯一文件名。
这里是UploadedFile
实例上使用的store
方法,用于存储新文件:
namespace Illuminate\Http;
/**
* Store the uploaded file on a filesystem disk.
*
* @param string $path
* @param array|string $options
* @return string|false
*/
public function store($path, $options = [])
{
return $this->storeAs($path, $this->hashName(), $this->parseOptions($options));
}
hashName()
方法来自于 Trait FileHelpers.php
namespace Illuminate\Http;
/**
* Get a filename for the file.
*
* @param string|null $path
* @return string
*/
public function hashName($path = null)
{
if ($path) {
$path = rtrim($path, '/').'/';
}
$hash = $this->hashName ?: $this->hashName = Str::random(40);
if ($extension = $this->guessExtension()) {
$extension = '.'.$extension;
}
return $path.$hash.$extension;
}
如果你遵循Laravel的逻辑,你可以使用Str::random(40)
这个Laravel提供的辅助函数来生成一个唯一的文件名。为了更加确保唯一性,你还可以在这个字符串后面附加当前的日期和时间。
$ext = pathinfo($url, PATHINFO_EXTENSION);
$filename = bcrypt($url).time().'.'.$ext;
/
,因此在 Linux 环境下这是一个非常糟糕的想法。 - Buddhi741
md5($url)
为该URL生成一个文件名。 - apokryfos