I want to add a feedback form in frontend, with an image upload field, How to save form data and images in database?
Magento – Magento 2 : How to upload image from frontend
frontendimage-uploadmagento2
Related Solutions
I assume you want to upload the image in a specific folder and when you edit one of your entities that has an image, you should see the image near the input with an option to delete.
If so, here is what you need to do.
You need to create a custom renderer for the image field.
Create the file app/code/local/[Vendor]/[Module]/Block/Adminhtml/[Entity]/Helper/Image.php
<?php
class [Vendor]_[Module]_Block_Adminhtml_[Entity]_Helper_Image extends Varien_Data_Form_Element_Image
{
protected function _getUrl()
{
$url = false;
if ($this->getValue()) {
$url = Mage::getBaseUrl('media').'/'.'your_folder'.
$this->getValue();
}
return $url;
}
}
now you have to make your form use this renderer. In the add/edit form you should have a line like this:
$fieldset = $form->addFieldset('....',array('legend' => ...)));
after this line add this:
$fieldset->addType(
'image',
Mage::getConfig()->getBlockClassName('[vendor]_[module]/adminhtml_[entity]_helper_image')
);
Now you should save the image when uploaded.
In your saveAction
add this below $data = $this->getRequest()->getPost();
$input = 'collar_image'; //the image input name
$destinationFolder = Mage::getBaseDir('media').DS.'your_folder';
$imageName = '';
try {
if (isset($data[$input]['delete'])) {
$imageName = '';
} else {
$uploader = new Varien_File_Uploader($input);
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
$result = $uploader->save($destinationFolder);
$imageName = $result['file'];
}
} catch (Exception $e) {
if ($e->getCode() != Varien_File_Uploader::TMP_NAME_EMPTY) {
throw $e;
} else {
if (isset($data[$input]['value'])) {
$imageName = $data[$input]['value'];
}
}
}
$data[$input] = $imageName;
Then continue the normal saving process.
Replace in the code above the values between []
with your real values.
- [Vendor] => your module namespace
- [Module] => your module name
- [Entity] => your entity name
Add Below code in n _prepareForm()
function inside
app/code/Namespace/Module/Block/Adminhtml/Module/Edit/Tab/Main.php
$fieldset->addField(
'profile',
'image',
[
'name' => 'profile',
'label' => __('Profile Image'),
'title' => __('Profile Image'),
'required' => false,
'disabled' => $isElementDisabled
]
);
Now in execute()
method of your save controller file. use below code to save and upload image.
app/code/Namespace/Module/Controller/Adminhtml/Index/Save.php
use Magento\Framework\App\Filesystem\DirectoryList;
$profileImage = $this->getRequest()->getFiles('profile');
$fileName = ($profileImage && array_key_exists('name', $profileImage)) ? $profileImage['name'] : null;
if ($profileImage && $fileName) {
try {
/** @var \Magento\Framework\ObjectManagerInterface $uploader */
$uploader = $this->_objectManager->create(
'Magento\MediaStorage\Model\File\Uploader',
['fileId' => 'profile']
);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
/** @var \Magento\Framework\Image\Adapter\AdapterInterface $imageAdapterFactory */
$imageAdapterFactory = $this->_objectManager->get('Magento\Framework\Image\AdapterFactory')
->create();
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->setAllowCreateFolders(true);
/** @var \Magento\Framework\Filesystem\Directory\Read $mediaDirectory */
$mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')
->getDirectoryRead(DirectoryList::MEDIA);
$result = $uploader->save(
$mediaDirectory
->getAbsolutePath('Modulename/Profile')
);
//$data['profile'] = 'Modulename/Profile/'. $result['file'];
$model->setProfile('Modulename/Profile'.$result['file']); //Database field name
} catch (\Exception $e) {
if ($e->getCode() == 0) {
$this->messageManager->addError($e->getMessage());
}
}
}
Best Answer
First, you should be add input type file at form and also add
enctype='multipart/form-data'
andAt controller, you need upload image via
Add below class in __construct functions and execute function of controller:
Note
$destinationPath
give the path tillmagentoDir/pub/media/custom_image
and $result content below