Magento: How to upload file?

In adminhtml, you might have the following code in any form. Here ‘logo‘ is the name of the input type file. Or, you may have any HTML Form with the File field in the frontend page. Remember that your form’s enctype should be multipart/form-data.


$fieldset->addField('logo', 'file', array(
	'label'     => 'Small Logo',
	'required'  => false,
	'name'      => 'logo',		
));

You can easily upload file using Varien_File_Uploader class. The class file path is lib/Varien/File/Uploader.php.

– In the code below, the file field name is ‘logo‘.
– You can add or remove allowed extension for upload through setAllowedExtensions function.
– If setAllowRenameFiles function’s parameter is set true, then the uploaded file name will be changed if some file with the same name already exists in the destination directory.
– The file is uploaded in media directory. You can add your own directory there. But remember that your directory should be writable.
– save function is used to save the file with a specific name and to a specific path.


if (isset($_FILES['logo']['name']) && $_FILES['logo']['name'] != '') {
	try {	
		$uploader = new Varien_File_Uploader('logo');
		$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
		$uploader->setAllowRenameFiles(false);
		$uploader->setFilesDispersion(false);
		$path = Mage::getBaseDir('media') . DS;
		// $path = Mage::getBaseDir('media') . DS . 'logo' . DS;
		$logoName = $_FILES['logo']['name'];
		$uploader->save($path, $logoName);
		
	} catch (Exception $e) {
		
	}
}

Hope this helps. Thanks.