#Can't save a file during "saving" function

4 messages · Page 1 of 1 (latest)

azure linden
#

I'm using a custom field that allows me to associate an image with an item. When the form is submitted, the field contains a Base64-encoded image.

I want to save the image file to the /public/storage/images/[item]/ folder and then update the "image" field with the file path before saving it to the database.

I've inserted the following function into the boot() method of the model:

    static::saving(function ($book) {
          $image = $book->image;
          $path = '/storage/images/books/';
          if ($image && preg_match('/^data:.*/', $image)) {
              try {
                  $a = explode(',', $image);
                  $b = explode(";", $a[0]);
                  $c = explode(":", $b[0]);
                  $d = explode("/", $c[1]);
                  $ext = pathinfo($d[1], PATHINFO_EXTENSION);
                  $name = uniqid() . '.' . $ext;
                  $encoded = $a[count($a) - 1];
                  $decoded = base64_decode($encoded);
                  try {
                      $fp = fopen($path . $name, 'w');
                      fwrite($fp, $decoded);
                      fclose($fp);
                      $book->image = $path . $name;
                  } catch (\Exception $e) {
                      $book->image = null;
                      Notification::make()
                            ->title($e->getMessage())
                            ->danger()
                            ->send();
                      return true;
                  };
          return true;
    });

The file save failed with an "access denied" error.
The permissions on the destination folder (which is linked) are "everyone => full control".

I don't understand where the problem is. Any ideas?

hybrid terraceBOT
#

To help others find answers, you can mark your question as solved via Right click solution message -> Apps -> ✅ Mark Solution

marsh shale
#

Sounds like your server isn't configured properly. Either just simply file permissions or something else.

fluid ether
#

If you are using the native fopen() function, you need to provide the full absolute path. You seem to just be using a /storage path relative to your Laravel root. Best to use Laravel's Storage facade, let it handle paths for you.