Magento – Magento 2 : Upload product image programatically

magento-2.1productproduct-images

I am new to Magento and i want upload upload product programmatically along with product image, i am using this code to implement, please check

try{
$_product->setName($product["name"]);
$_product->setTypeId('simple');
$_product->setAttributeSetId(4);
$_product->setSku($product["sku"]); // this must be unique everytime and get the exception in frontend
$_product->setWebsiteIds(array(1));
$_product->setVisibility(4);
$_product->setDescription($product["description"]);
$_product->setPrice($product["price"]);


//$imagePath = $product['imgpath'];

$_product->setMediaGallery(array('images'=>array (),'values'=>array ())); 
$_product->addImageToMediaGallery('https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg', array('image', 'small_image', 'thumbnail'),false);
// $_product->setImage('https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg');

// $_product->setSmallImage('/testimg/test.jpg');

// $_product->setThumbnail('/testimg/test.jpg');
$_product->setStockData(array(
        'use_config_manage_stock' => 0, //'Use config settings' checkbox
        'manage_stock' => 1, //manage stock
        'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
        'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
        'is_in_stock' => $product['stockstatus'], //Stock Availability
        'qty' =>  $product['quantity']
        )
    );
$_product->save();
}                 
catch(\Exception $e) { 
 echo $e->getMessage();
}

i provided the static path for the image and its opening in the browser, but getting error The image does not exist. while uploading product.
please suggest.

Best Answer

The 1st parameter of addImageToMediaGallery is the local path of the image, NOT remote path. Of course we can have some tweaks. Just download the images to a temporary folder, then add them into the product gallery.

/** @var string $tmpDir */
$tmpDir = $this->directoryList->getPath(DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . 'tmp';
/** create folder if it is not exists */
$this->file->checkAndCreateFolder($tmpDir);
/** @var string $newFileName */
$newFileName = $tmpDir . baseName($imageUrl);
/** read file from URL and copy it to the new destination */
$result = $this->file->read($imageUrl, $newFileName);
if ($result) {
    /** add saved file to the $product gallery */
    $_product->addImageToMediaGallery($newFileName, $imageType, true, $visible);
}

Subsitute $imageUrl into your image remote URL. You should inject \Magento\Framework\App\Filesystem\DirectoryList in order to use $this->directoryList and get constant DirectoryList::MEDIA. Also, you need to inject \Magento\Framework\Filesystem\Io\File to use $this->file.

Related Topic