0

I'm trying to send an image object from vue frontend to laravel controller, so that it can be stored in the public storage but the image gets destroyed. The stored image file can't be opened and shows an error.

In this component:

<input v-if="!state.image" class="input-file" type="file" @change="onFileChange">

these functions convert the input image to base64 format:

const createImage = (file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
        state.image = e.target.result;
    };
    reader.readAsDataURL(file);
}

const onFileChange = (e) => {
    state.path = e.target.files[0].name
    const files = e.target.files;
    if (!files.length)
        return;
    createImage(files[0]);
}

and send it via ajax request:

axios.post('/store', state)
    .then(res => {
        state.error = false
        router.push({name: 'artwork'})
    })
    .catch(err => {
        state.error = true
        setTimeout(() => state.error = false, 5000)
});

to MediaController.php:

<?php

namespace App\Http\Controllers;

use App\Models\Artwork;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;


class MediaController extends Controller
{
    public function store(Request $request)
    {
        $artwork = new Artwork;

        $artwork->name = $request->name;
        $artwork->path = '/storage/app/public/' . $request->path;
        $artwork->save();

        Storage::disk('public')->put($request->path, $request->image);

        return response()->json(null, 200);
    }
}

It looks like the base64 image data in $request->image turns out broken and is saved in /storage/app/public/1.jpg.

How can I get the image from the vue component to the controller and then to the public storage without breaking it?

1 Answer 1

1

I figured that vue encodes the image to base64 so the solution was to decode it back in laravel.

I had to add these lines to MediaController.php:

$image = str_replace('data:image/jpeg;base64,', '', $request->image);

Storage::disk('public')->put($request->path, base64_decode($image));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.