Skip to content
Advertisement

Laravel malformed UTF-8 characters, possibly incorrectly encoded using image intervention

I have a laravel project that has a image upload. I used image intervention library for uploading. The problem is i got a 500 error and saying Malformed UTF-8 characters, possibly incorrectly encoded. But when I look my directory for saving, the image was saved but the data was not saved to the database. Only the image was saved. Seems like the image save was successful but the request is not. What seems to be the problem?

Controller

 public function store(Request $request)
    {
        $product = new Product;
        $validator = Validator::make($request->all(), [
            'product_name' => 'required',
            'barcode' => 'required|unique:products',
            'price'=> 'required',
            'category' => 'required',
            'supplier' => 'required',
            // 'image' => 'required|image64:jpeg,jpg,png'
        ]);

        if ($validator->fails()) {
            $errors = json_encode($validator->errors());
            return response()->json([
                'success' => false,
                'message' => $errors
            ],422);
        } else {
            $product->barcode = $request->barcode;
            $product->product_name = $request->product_name;
            $product->price = $request->price;
            $product->quantity = 0;
            $product->category = $request->category;
            $product->supplier_id = $request->supplier;

            //image
            $imageData = $request->image;
            $fileName = time().'.'. explode('/', explode(':', substr($imageData, 0, strpos($imageData, ';'))) [1])[1];
            $product->image = Image::make($request->image)->save(public_path('img/').$fileName);

            $product->save();

            broadcast(new ProductsEvent(Auth::user()->name, 'add', $product))->toOthers();
        }
    }

Vue component event when form is changed

  onFileChange(e) {
                let file = e.target.files[0];
                console.log(file);
                var reader = new FileReader();
                reader.onloadend = (file)=>{this.image = reader.result}
                reader.readAsDataURL(file);
            },        

Advertisement

Answer

The problem was this line, I was saving the actual image object in the db.

 $product->image = Image::make($request->image)->save(public_path('img/').$fileName);

I changed it into

$imageData = $request->image;
$fileName = time().'.'. explode('/', explode(':', substr($imageData, 0, strpos($imageData, ';'))) [1])[1];

Image::make($request->image)->save(public_path('img/').$fileName);

$product->image = $fileName;
$product->save();;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement