0

In Magento, I am building a bulk image upload feature.
Here user can upload images as "sku_1.jpg, sku_2.jpg, sku_3.jpg ".
Now I need to set "sku_1.jpg" as the main image, thumbnail.

I used the following code for it. But some times it's working and some times it failed.

     try{
    $data[] = ['sku' => "sku" , 'image_name'=>"image",'status'=>"status"];
    foreach($files as $file){
        $image_count++;
        unset( $file_to_sku);            

        $file_name=$file["name"];
        $file_tmp=$file["tmp_name"];
        $generic_path = $vendorId.'/'.str_replace("-", "", date("Y-m-d"));
        if(!is_dir($path."/media/import/".$generic_path)) {          
            mkdir($path."/media/import/".$generic_path,0777,true);
        } 
        $image_path = $path."/media/import/".$generic_path.'/'.$file_name;
        $ext=pathinfo($file_name,PATHINFO_EXTENSION);

        if(in_array($ext,$extension))
        {                   
            move_uploaded_file($file_tmp,"pub/media/import/".$generic_path.'/'.$file_name);
            $base_filename =  pathinfo($file_name, PATHINFO_FILENAME);
            $fileNameNoExtension = preg_replace("/\.[^.]+$/", "", $file["name"]);
            $file_to_sku = explode("_",$base_filename);                 
            $product_image_sku = $file_to_sku[0];                         
            if($product_image_sku!=""){
                $prod =  $this->_vproducts->getVendorProductsByVendorSkuId($vendorId,$product_image_sku);
                $vend_prod_count = count($prod->getData());                       
                if($vend_prod_count > 0){
                    $product = $this->_objectManager->create('Magento\Catalog\Model\Product')->load($prod->getProductId());    
                     $prod_media = $product->getMediaGalleryImages();
                    $existingMediaGalleryEntries = $product->getMediaGalleryEntries();
                    $product_status=$product->getStatus();
                    $cmp_image=$product_image_sku."_1";
                    $productRepository = $this->_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
                    $ext_images = array();
                    if($product_status == 2){
                        if($existingMediaGalleryEntries){
                            foreach ($existingMediaGalleryEntries as $key => $entry) {    
                                $new_img=basename($entry['file']);
                                $ext_images[]=$new_img;
                                if($new_img==$file["name"]){                               
                                   $this->imageProcessor->removeImage($product, $entry['file']);
                                    unset($existingMediaGalleryEntries[$key]);            
                                }                                       
                                $product->setMediaGalleryEntries($existingMediaGalleryEntries);
                                $this->productRepository->save($product);                 
                            }                                    
                        }
                    }
                    if(count($prod_media) <= 6){                          
                      /*Add Images To The Product*/
                        if($file_to_sku[1] <= 6){
                            if( $product_status == 2){
                                $cmp_image=$product_image_sku."_1";                        
                                if($fileNameNoExtension == $cmp_image){
                                    $product->setBaseImage($image_path)
                                       // ->setSmallImage($image_path)
                                       // ->setThumbnail($image_path)
                                        ->addImageToMediaGallery($image_path,array('image', 'small_image', 'thumbnail'),false, false);
                                        $product->save();

                                    //                                        
                                }else{                                    
                                    $product->addImageToMediaGallery($image_path, null, false, false);                                   
                                }
                                if($product->save()){
                                    $data[] = ['sku' => $product_image_sku , 'image_name'=>$file["name"],'status'=>'success'];
                                    $success++;
                                }else{
                                    $data[] = ['sku' => $product_image_sku , 'image_name'=>$file["name"],'status'=>'Image not saved'];
                                }
                            }elseif(!in_array($file["name"],$ext_images)){    

                                if($fileNameNoExtension == $product_image_sku."_1")
                                    $product->addImageToMediaGallery($image_path, array('image', 'small_image', 'thumbnail'), false, false);
                                else
                                    $product->addImageToMediaGallery($image_path, null, false, false);
                                if($product->save()){
                                    $data[] = ['sku' => $product_image_sku , 'image_name'=>$file["name"],'status'=>'success'];
                                }else{
                                    $data[] = ['sku' => $product_image_sku , 'image_name'=>$file["name"],'status'=>'Image not saved'];
                                }
                            }
                        }else{
                            $data[] = ['sku' => $product_image_sku , 'image_name'=>$file["name"],'status'=>'image is not a valid extension'];
                        }
                    }else{                           
                        $data[] = ['sku' => $product_image_sku , 'image_name'=>$file["name"],'status'=>'product already have 6 images'];
                    }
                }else{
                    $data[] = ['sku' => $product_image_sku , 'image_name'=>$file["name"],'status'=>'product sku not found']; 
                }
            }else{                        
                $data[] = ['sku' => $product_image_sku , 'image_name'=>$file["name"],'status'=>'product sku not found'];
            }                     
        }else{                   
            $data[] = ['sku' => $product_image_sku , 'image_name'=>$file["name"],'status'=>'image is not a valid extension'];
            //array_push($error,"$file_name, ");
        }
    }

What was wrong in my code? please help me.

  • could you please post your full code? – Keyur Shah Apr 19 at 10:10
  • updated full code – Dinesh Apr 19 at 10:19
  • I tried following code as well.... but not worked. $mediaGalleryEntriesTemp = []; foreach ($product->getMediaGalleryEntries() as $item) { $new_img=basename($item['file']); if ($new_img == $cmp_image) { $item->setTypes(['image', 'small_image', 'thumbnail']); } $mediaGalleryEntriesTemp[] = $item; $i++; } $product->setMediaGalleryEntries($mediaGalleryEntriesTemp); $this->productRepository->save($product); – Dinesh Apr 19 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.