mjawad096 / laravel-grapesjs

This package provide an esay way to integrate GrapesJS into your laravel proejct.
MIT License
107 stars 54 forks source link

Image upload on aws s3 not working #60

Closed SojebSikder closed 1 year ago

SojebSikder commented 1 year ago

I tried local file storage for Image uploading and worked perfectly fine, But when I switched to s3, gives me s3 error.

found 1 error while validating the input provided for the getobject operation:\n[key] expected string length to be >= 1, but found string length of 0 laravel

Then I implemented own AssetController, that worked fine.

mjawad096 commented 1 year ago

Hi there, what changes you made in your Asset Controller?

SojebSikder commented 1 year ago

I write this code, And worked completely fine.

web.php

    Route::prefix('laravel-grapesjs')
        ->name('laravel-grapesjs.')
        ->group(function () {
            Route::post('asset/store', [AssetController::class, 'store'])->name('asset.store');
        });

AssetController.php:

<?php

namespace App\Http\Controllers\Admin\Page\PageBuilder;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class AssetController extends Controller
{
    public function __construct()
    {
        $this->storage = Storage::disk(config('laravel-grapesjs.assets.disk'));
        $this->diskPath = config('laravel-grapesjs.assets.path') ?? 'laravel-grapesjs/media';
    }

    public function store(Request $request)
    {
        try {
            $this->validate($request, [
                'file' => 'required|array',
                'file.*' => 'required|file'
            ]);

            // upload files from request
            $file_name = $request->file('file');
            $files = $file_name;

            if (!is_array($files)) {
                $files = [$files];
            }

            $uploaded_files = [];

            foreach ($files as $file) {
                $uploaded_files[] = $this->uploadSingle($file);
            }

            return response()->json([
                'data' => $uploaded_files
            ]);
        } catch (\Throwable $th) {
            throw $th;
        }
    }

    private function uploadSingle($file)
    {

        $file_name = $file->getClientOriginalName();
        $file_path = $this->diskPath . '/' . $file_name;

        $this->storage->put($file_path, file_get_contents($file->getRealPath()));
        return $this->storage->url($file_path);
    }}