Magento – Magento 2.1.6 Unable to write file into directory \D:/XAMPP/htdocs/magento/pub/media/catalog/product\cache

errormagento2magento2.1.6

The error message appears every time I upload image on a product.

The complete message is:

Unable to write file into directory \D:/XAMPP/htdocs/magento/pub/media/catalog/product\cache\914b1ba9268f8c1d0e58a8e7ce614488/s/o. Access forbidden.

The version of Magento I installed is 2.1.6, on XAMPP for Windows. The version of PHP installed in XAMPP is PHP 5.6.20.

I've tried:

  • Editing vendor/magento/module-catalog/Model/View/Asset/Image.php as stated in this answer, that is, replacing all occurrences of DIRECTORY_SEPARATOR with '/' and editing getRelativePath function
  • …and this answer, that instructs to remove DIRECTORY_SEPARATOR in line 226
  • chmod -R 777 ./ on /XAMPP/htdocs/magento/pub/media/catalog/product with Bash, in case it has something to do with the permission

And nothing above has worked for me, except that the first option I tried give me a new error when I upload image on a product:

The file "D:/XAMPP/htdocs/magento/pub/media/tmp/catalog/product/s/o/test_image.png" doesn't exist or not a file

But when I check the file, it exists there!:

enter image description here

Is there anything I can do to solve this problem?
Any help would be appreciated. Thanks!

Best Answer

There is a simple way to solve this issue: in vendor/magento/module-catalog/Model/View/Asset/Image.php:226 remove the 'DIRECTORY_SEPARATOR'

private function getRelativePath($result)
{
$result = $this->join($result, $this->getModule());
$result = $this->join($result, $this->getMiscPath());
$result = $this->join($result, $this->getFilePath());
return $result;
}

and: /vendor/magento/module-catalog/Model/View/Asset/Image.php:130 replace DIRECTORY_SEPARATOR to '/'

 private function join($path, $item)
    {
        return trim(
            $path . ($item ? '/' . ltrim($item, '/') : ''),
            '/'
        );
    }

PHP accepts both \ and / as valid path separators. So just use / in your code.