Domanda

I am making custom Magento API to create products. I can make products using custom API. Now my requirements is to upload multiple images to that API.

Can anyone helps me for reference code to upload multiple product images programmatically ??

Following example works for me for creating simple procuts.

$simpleProduct->setTypeId('simple')
->setAttributeSetId($attributeSetId)
->setWebsiteIds([1])
->setName($params['product_name'].' '.$size_label)
->setSku('SKU_'.time().$size_label)
->setUrlKey(str_replace(" ","_",$params['product_name'])."_".time())
->setPrice($params['price'])
->setSize($size_value) // Set the 'color' attribute option value
->setVisibility(1)  
->setStatus(1)
->setCategoryIds($CategoryIds)
->setStockData(['use_config_manage_stock' => 1, 'qty' => $size_qty, 'is_qty_decimal' => 0, 'is_in_stock' => $in_stock])
->setData('brand',$params['brand'])     
->setData('color',$params['color'])     
->setData('material',$params['material'])   
->setData('type',$params['type'])       
->setData('condition',$params['condition']);
$simpleProduct = $productRepository->save($simpleProduct);
$associatedProductIds[] = $simpleProduct->getId();
$simple_product_id = $simpleProduct->getId();

enter image description here

If anyone please guide me for this requirements.

È stato utile?

Soluzione

STEP 1 : First upload all images to server and make array of it.

Sample Code For Multiple Image Upload:

//-----------------------------------------------------     
    // Image upload ST
    $result = $full_img_path = array();
    if ($_FILES['product_images']['name']){
        
        $imgcount = count($_FILES['product_images']['name']);
        if($imgcount){
            
            for($i = 0; $i<$imgcount; $i++){
            
                $temp_name = $_FILES['product_images']['tmp_name'][$i];
                $name      = $_FILES['product_images']['name'][$i];
                $type      = $_FILES['product_images']['type'][$i];
                $size      = $_FILES['product_images']['size'][$i];
            
                try {
                    
                    // init uploader model.
                    $uploader = $objectManager->create('Magento\MediaStorage\Model\File\Uploader',['fileId' => 'product_images['.$i.']']);
                    $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                    $uploader->setAllowRenameFiles(true);
                    $uploader->setFilesDispersion(true);
                    $uploader->setAllowCreateFolders(true);
                
                    //public_html/popzaar/pub/media/catalog/product/0/1
                    //"/home/wnutcom/public_html/popzaar/pub/media/catalog/product"
                    $mediaUrl = $this->fileSystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath('/catalog/product');
                    $img_uploder = $uploader->save($mediaUrl);
                    //$img_uploder_array = array($img_uploder);
                        
                    $img_path = $img_uploder['path'];
                    $img_file = $img_uploder['file'];                   
                    $full_img_path[] = $img_path.$img_file;
                    
                    
                } catch (Exception $e) {\Zend_Debug::dump($e->getMessage());
            
                    return array(array("status"=>0,"message"=>"Image upload Error ".$ex->getMessage()));
                }
            
            }
        }
    }
    // Image upload test EN
    //-----------------------------------------------------

Step 2 : Assign all images to product ID

Sample code for image link to product

 // product object ST
if(!empty($full_img_path)){
    foreach($full_img_path as $img){
    $uploaded_productid = $objectManager->create('Magento\Catalog\Model\Product')->load($simple_product_id);
    $uploaded_productid->addImageToMediaGallery($img, array('image', 'small_image', 'thumbnail'), false, false);
    $uploaded_productid->save();
   }
}
    // product object EN

NOTE : I am using same product id from your sample code you can change it as per your requirements. This code works for me in simple product as well as configurable products in Magento 2.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top