2

There is a custom folder "productimages" in root path "localhost/magento/productimages". In this folder "productimages", there are lots of images. I want to save that images in products using object manager. So is there any way to do it ?

<?php 
ini_set('display_errors', 1);
error_reporting(E_ALL);
use \Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();
$fileSystem = $object_Manager->create('\Magento\Framework\Filesystem');
$mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();


$state = $object_Manager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product_id = 19;
$product = $object_Manager->get('Magento\Catalog\Model\Product')->load($product_id);
$productRepository = $object_Manager->create('Magento\Catalog\Api\ProductRepositoryInterface');

$image =  $mediaPath.'imagiing.jpg';

$attributeImage = array('image', 'small_image', 'thumbnail');
// $productRepository->save($product);

$product->addImageToMediaGallery($image, $attributeImage, false, false);
$product->save();

Given code works only with the "pub/media" folder.

Any help will be appreciated...

Thank you.

1 Answer 1

0

Please try with below code to create directory in root :

<?php 
ini_set('display_errors', 1);
error_reporting(E_ALL);
use \Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();
//$fileSystem = $object_Manager->create('\Magento\Framework\Filesystem');

$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');


$mediaPath = $directory->getRoot().'productimages';


$state = $object_Manager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product_id = 19;
$product = $object_Manager->get('Magento\Catalog\Model\Product')->load($product_id);
$productRepository = $object_Manager->create('Magento\Catalog\Api\ProductRepositoryInterface');

$image =  $mediaPath.'imagiing.jpg';

$attributeImage = array('image', 'small_image', 'thumbnail');
// $productRepository->save($product);

$product->addImageToMediaGallery($image, $attributeImage, false, false);
$product->save();

hope very helpful to you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.