在使用Postman测试时,在Laravel中上传和调整文件大小时出错

wz1wpwve  于 2023-11-18  发布在  Postman
关注(0)|答案(1)|浏览(169)

我正在使用Postman版本0.12.1插件在Visual Studio代码中测试上传和重定向图像文件,但我得到了一个错误,我不知道如何修复。
这是我在Postman上收到的错误消息
x1c 0d1x的数据
这是我发送来测试API的form-data



这是我的GalleryRepository代码:

public function create(array $data)
    {
        try{
            return DB::transaction(function()use($data){
                // Define the maximum width and height
                $maxWidth = 1000;
                $maxHeight = 1000;
                // resize the image while maintaining the aspect ratio
                $data['name'] = request('name')->resize($maxWidth, $maxHeight, function($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize(); // prevent the image from upscaling
                });

                $subfolder = date('Y') . '/' . date('m');
                $img_path = "assets/img/{$data['type']}/gallery/{$subfolder}";
                $data['name'] = $data['name']->store($img_path, 'public');
                return Gallery::create($data);
            });
        }catch(Exception $error){
            $message = $error->getMessage()??"INSERT_ERR";

            /**
             * known code error db
             * 23000 duplicate entry
             * @see https://dev.mysql.com/doc/mysql-errors/8.0/en/server-error-reference.html
             */
            if($error->getCode()==='23000'){
                $message = "ERR_DUPLICATE_ENTRY";
            }

            return ['status'=>'ERR','message'=>$error];
        }
    }

字符串

StoreGalleryRequest文件目前只有1条规则:

public function rules(): array
    {
        return [
            'name' => 'required|image|mimes:jpg,png',
        ];
    }

    protected function passedValidation(): void
    {
        $data = $this->validated();

        $this->replace($data);
    }

mv1qrgav

mv1qrgav1#

要调用resize(),请尝试使用库Intervention/Image
composer require intervention/image
下面是GalleryRepository的示例代码:

try{
    //..
        $image = Image::make(request('name'));

        // resize the image while maintaining aspect ratio
        $image->resize($maxWidth, $maxHeight, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize(); // prevent the image from upscaling
        });

        $subfolder = date('Y') . '/' . date('m');
        $img_path = "assets/img/{$data['type']}/gallery/{$subfolder}";
        $imageName = uniqid() . '.jpg'; // generate a unique filename
        $image->save(public_path("$img_path/$imageName"));

        $data['name'] = "$img_path/$imageName";

        return Gallery::create($data);
    })
}

字符串

相关问题