Magento – Magento 2 : Error when try to set image for product and save

imagemagento2PHPproduct

When i'm trying to set image for the product

$configurable->setMediaGallery(array('images'=>array (), 'values'=>array ()));
$path = $this->helper->uploadImage($data->main_image);
if ($path && file_exists($path)) {
    $configurable->addImageToMediaGallery($path, array('image', 'small_image', 'thumbnail'), true, false);
}

and then when save it i'm getting an error

Exception #0 (Magento\Framework\Exception\FileSystemException): The file "… pub/media/tmp/catalog/product/8/1/81cz5-izU0L.jpg" doesn't exist or not a file

Looks like some permission issue but i've checked all directories have all needed access.
Any suggestions?
Thanks.

Best Answer

The file path should be relative to media folder. Below I'll try to explain why.

So addImageToMediaGallery calls Model\Product\Gallery\Processor.php::addImage

 $file = $this->mediaDirectory->getRelativePath($file);
 if (!$this->mediaDirectory->isFile($file)) {
      throw new LocalizedException(__('The image does not exist.'));
 }

You can do a debug of the $file, and then keep digging which will eventually bring you to Magento\Framework\Filesystem\Directory\Read

Particularly this line 219: $this->driver->getAbsolutePath($this->path, $path)

Now, if your path was "/fullpath/pub/media/../file.jpg" which you passed to addImageToMediaGallery, then by debugging the result of getAbsolutePath call, you will get something like this:

/fullpath/pub/media/fullpath/pub/media/../file.jpg

So your path is prefixed with the full server path to your media folder and that's make it invalid and therefore exception 'The image does not exist.' is thrown.

Hope it makes it more clear now.

Related Topic