Laravel 5.5 Storing image from base64 string

In Laravel 5.5 project, I have successfully saved the info into product table in MySQL. The info include a base64 string which is an image basically. However, I'm facing an issue while stroing the image in public folder of the laravel project. Below is my code for the ProductController.php

public function update(Request $request, $id)
{
    $data = $request->validate([
        'product_name' => 'required',
        'description' => 'required',
        'rating' => 'required'
    ]);

    $uploaded_image = $request->input('uploaded_image');
    $data['uploaded_image'] = $uploaded_image['value']; // base64 string
    $product = Product::findOrFail($id);
    $product->update($data);
    // the data stored into the database with no issue

    $image_base64 = base64_decode($uploaded_image['value']);
    $path = public_path();
    $success = file_put_contents($path, $image_base64.".png");

    return response()->json($data);
}

I see the following error below:

message:"file_put_contents(C:\xampp\htdocs\laravel-api\public): failed to open stream: Permission denied"

By seeing different sources, I did the following, but nothing changed.

  1. php artisan clear-compiled
  2. Icacls public /grant Everyone:F
  3. composer dump-autoload

Any idea?

Upvotes: 1

Views: 8253

Answers (2)

Mohamed Raza
Mohamed Raza

Reputation: 174

Instead of giving permission as icacls "public" /grant USER:(OI)(CI)F /T we can store the files/ images as follows

Storage::disk('public')->put('Items_attachments/'.$img_name, base64_decode($data));

Items_attachments - is the sub folder inside the public

$img_name - the name for base64 string

$data - is the decoding object

Upvotes: 0

Hiren Gohel
Hiren Gohel

Reputation: 5042

As per our discussion you need to give permissions like:

icacls "public" /grant USER:(OI)(CI)F /T

Where USER is your pc's user

Also, if you want to save base64 image in storage path then use the following code:

//Function to save a base64 image in laravel 5.4
public function createImageFromBase64(Request $request){

      $file_data = $request->input('uploaded_image');
      //generating unique file name;
      $file_name = 'image_'.time().'.png';
      //@list($type, $file_data) = explode(';', $file_data);
      //@list(, $file_data)      = explode(',', $file_data);
      if($file_data!=""){
        // storing image in storage/app/public Folder
        \Storage::disk('public')->put($file_name,base64_decode($file_data));     
      }
}

Hope this helps you!

Upvotes: 6

Related Questions