Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload image of product from front end in magento

I'm trying to upload the image of the product in admin panel. It's working fine but now I want to upload the image of the product in front end.

I mean customer can upload the image of the product from the front end. So how this is possible?

like image 285
Navin Parmar Avatar asked Apr 09 '15 05:04

Navin Parmar


1 Answers

First upload image in media/import

if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '') {
    $fileName       = $_FILES['file']['name'];
    $fileExt        = strtolower(substr(strrchr($fileName, "."), 1));
    $fileNamewoe    = rtrim($fileName, $fileExt);
    $fileName       = str_replace(' ', '', $fileNamewoe) . $fileExt;

    $uploader       = new Varien_File_Uploader('file');
    $uploader->setAllowedExtensions(array('png', 'jpg', 'jpeg')); //allowed extensions
    $uploader->setAllowRenameFiles(false);
    $uploader->setFilesDispersion(false);
    $path = Mage::getBaseDir('media') . DS . 'import';
    if(!is_dir($path)){
        mkdir($path, 0777, true);
    }
    $uploader->save($path . DS, $fileName );
}

Now save product with uploaded image

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product')->load($id);
$product->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
$imagePath = Mage::getBaseDir('media') . DS . 'import/'. $fileName;
$product->addImageToMediaGallery($imagePath,array('image', 'small_image', 'thumbnail'),true,false);
$product->save();
like image 163
Laxman Singh Avatar answered Sep 29 '22 13:09

Laxman Singh