我正在构建一个服务来上传图像与laravel和存储在亚马逊网络服务s3存储桶,这是负责存储图像的函数。
public function fromUrl(Request $request)
{
$validator = Validator::make($request->all(), [
'files' => 'required|array|min:1',
'files.*' => 'string',
]);
if (!$validator->fails()) {
$paths = [];
foreach ($validator->validate()['files'] as $file) {
$url = config('services.s3.host') . Storage::disk('s3')->put('images/public', file_get_contents($file), 'public');
array_push($paths, $url);
}
return $paths;
} else {
throw new ValidateException([
'message' => $validator->errors()->toArray(),
'rules' => $validator->failed()
]);
}
}请求正文如下所示。
{
"files": [
"https://image-url-1",
"https://image-url-2"
]
}我希望保存图像时返回的路径是这样的。
[
"https://my-bucket-url/images/public/random-name-for-image1",
"https://my-bucket-url/images/public/random-name-for-image2"
]但是相反,我得到了以下结论。
[
"https://my-bucket-url/1",
"https://my-bucket-url/1"
]发布于 2020-04-10 06:34:45
您在示例中滥用了put。
首先,第一个参数是path加上filename,您没有文件名随机逻辑。第三个参数是选项数组。
$randomFileName = uniqid(rand(), true);
$path = 'images/public/' . $randomFileName;
Storage::disk('s3')->put($path, file_get_contents($file));这段代码将在images/public/$randomFileName中保存一个元素。要返回正确的路径,可以使用url()方法。
$url = Storage::disk('s3')->url($path);
array_push($paths, $url);https://stackoverflow.com/questions/61130870
复制相似问题