gpt4 book ai didi

php - 我该如何解决 "Type error: Argument 2 passed to ... must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile"?

转载 作者:搜寻专家 更新时间:2023-10-31 21:22:22 25 4
gpt4 key购买 nike

我的 Controller 是这样的:

public function store(CreateProductRequest $request)
{
...
$result = $this->product_service->createProduct($param,$photo);
...
}

我的服务是这样的:

public function createProduct($param, UploadedFile $photo=null)
{
dd($photo);
if($photo) {
$fileName = str_random(40) . '.' . $photo->guessClientExtension();
$param['photo'] = $fileName;
$param['photo_list'] = json_encode(['id'=>1,'name'=>$fileName]);
}
...
if(is_array($result) && count($result)>1 && $result[0])
$this->savePhoto($photo, $fileName,$result[1]->id);
...
return $result;
}

private function savePhoto(UploadedFile $photo, $fileName, $id)
{
$destinationPath = public_path() . DIRECTORY_SEPARATOR . 'img'. DIRECTORY_SEPARATOR .'products'.DIRECTORY_SEPARATOR.$id;
$photo->move($destinationPath, $fileName);
resize_image($fileName,250,'products',$id);
return $fileName;
}

Symfony\Component\HttpFoundation\File\UploadedFile 是这样的:https://pastebin.com/KLfnXZJV

当变量 $photo 不是数组或只有 1 个数据时,我执行 dd($photo);,它显示结果

但是当变量$photo是数组时,我做dd($photo);,存在错误:

Type error: Argument 2 passed to App\Services\ProductService::createProduct() must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile, array given

我该如何解决这个问题?

最佳答案

这里的问题是您要么得到一个文件,要么得到一个文件数组。创建产品是否支持上传多个文件?如果没有,你可以这样做:

// If file is inside an array, pull it out
if (is_array($photo) && $photo[0] instanceof UploadedFile) {
$photo = $photo[0];
}

// Run upload
$result = $this->product_service->createProduct($param, $photo);

如果您需要上传多个文件的能力,则需要做一些事情。首先,您不能将方法类型提示为 UploadedFile。相反,将其类型提示为数组:

public function createProduct($param, array $photos = [])

然后在您的 createProduct 逻辑中,您需要遍历照片数组并单独保存它们。

最后,在您的 Controller 中,您需要执行与第一个建议相反的操作,而不是从数组中提取,您需要将其放入一个数组中:

if ($photo instanceof UploadedFile) {
$photo = [$photo];
}

关于php - 我该如何解决 "Type error: Argument 2 passed to ... must be an instance of Symfony\Component\HttpFoundation\File\UploadedFile"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44026297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com