4/28/2011

How to upload file in magento

If you are making your custom module in magento and if you unable to use default magento file upload then you can use magento custom file uploading code to upload file.

// If you want to upload files under media folder
$absolute_path = Mage::getBaseDir('media') . DS ;
$relative_path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
// File Upload
$files = $_FILES['file_upload']['name'];
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('file_upload');
// Any 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());
}
// Your uploaded file Url will be
echo $file_url = $relative_path.$files;
}

2 comments:

  1. how to multiple image upload in magento product page?

    ReplyDelete
    Replies
    1. Watch this video to find your answer

      http://www.youtube.com/watch?v=J4qY_IdqNzE

      Delete