Magento – magento 2 / can’t set addImageToMediaGallery path

csvmagento2PHP

i created php file in root folder and trying to create simple product programatically in magento 2. testimg folder locating in root. I always thow the error: The image does not exist. Here is code:

$_product->setImage('testimg/test.jpg');
$_product->setSmallImage('testimg/test.jpg');
$_product->setThumbnail('testimg/test.jpg');
$_product->addImageToMediaGallery(
    'testimg/test.jpg',
    null,
    false,
    false
);
$_product->addImageToMediaGallery(
    'testimg/test.jpg',
    null,
    false,
    false
);

when i put 'testimg' folder in 'pub/media' and run script:

$dir = $objectManager->get('Magento\Framework\App\Filesystem\DirectoryList');
$_product->addImageToMediaGallery(
    $dir->getPath('media') . '/testimg/test.jpg',
    null,
    false,
    false
);

i receive next error:
The file "/home/xxx/pub/media/tmp/catalog/product/t/e/test.jpg" doesn't exist or not a file.
Why magento looking for my file in tmp/catalog/product/t/e/ ?

Best Answer

In Magento 2, the root folder is not by default accessible. You need to put your testimg folder in pub/media to make it work. Move your folder to pub/media and update your code like below.

Here you are using an external php file, so you can do it like below.

$obj = $bootstrap->getObjectManager();
$dir = $obj->get('Magento\Framework\App\Filesystem\DirectoryList');

$_product->addImageToMediaGallery(
    $dir->getPath('media').'/testimg/test.jpg',
    null,
    false,
    false
);
$_product->save();