5

I uploaded product image programatically by using following code.

$files = $_FILES['images']['name'];
$f = substr($files,0,1);
$s= substr($files,1,1);
$absolute_path = Mage::getBaseDir('media').DS.'catalog'.DS.'product'.DS.$f.DS.$s; 
if(isset($files) && $files != '') 
{   
    try 
    { 
          if(file_exists($absolute_path.DS.$files)) 
          { 
               $var = rand(0,99); 
               $files = $var.'_'.$files; 
          } 
          // Starting upload 
          $uploader = new Varien_File_Uploader('images'); 
          //Here 4 extention would work 
          $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); 
          $uploader->setAllowRenameFiles(false); 
          //false -> get the file directly in the specified folder 
          //true -> get the file in the product like folders /media/catalog/product/file.gif 
          $uploader->setFilesDispersion(false); 
          //We set media as the upload dir 
          $uploader->save($absolute_path, $files);

    } 
    catch(Exception $e) 
    { 
          Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); 
    } 

$absolute_path = Mage::getBaseDir('media').DS.'catalog'.DS.'product'.DS.$f.DS.$s.DS.$files;

$mediaArray = array(
        'thumbnail'   => $absolute_path,
        'small_image' => $absolute_path,
        'image'       => $absolute_path,
    );
    foreach($mediaArray as $imageType => $files)
    {
        $filePath = $files;
        if(file_exists($filePath)) 
        {
            try
            {
             $product->addImageToMediaGallery($filePath, $imageType, false);
            } 
            catch (Exception $e)
            {
                echo $e->getMessage();
            }
        } 
        else 
        {
            echo "Product does not have an image or the path is incorrect. Path was: {$filePath}<br/>";
        }
    }
}

It is added in backend but in the table

catalog_product_entity_media_gallery_value

uploaded images disabled column value is 1.

If I upload image from backend, the uploaded image disabled column value is set as 0. How to fix this.

3

The addImageToMediaGallery method accepts a fourth argument (exclude - a boolean) that sets the image to enabled or disabled. It defaults to true, which means exclude from the gallery/disabled.

Change your code to

$product->addImageToMediaGallery($filePath, $imageType, false, false);

Also, I don't think you need to loop through $mediaArray to create each size you can call the method once like

$product->addImageToMediaGallery(
    $filePath,
    array('thumbnail', 'small_image', 'image'), 
    false, 
    false
 );

Your Answer

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

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