I am trying to Add image upload in the Gift Message. To achieve , created a Field: image_url in the Table: gift message using db_schema.xml and used the extension_attributes.xml to set and retrieve the value.
I have added the file upload element in the gift-message-form.html. But unable to pass the uploading file information to gift Message API model (Because gift message using /carts/mine/gift-message API).
Can anyone explain with an example how to upload the file using the controller with Ajax and store the uploaded file name in the Gift message table along with this record.
Thanks in Advance
Hello @Musammil
So you need to upload the product image in Magento 2 from controller file? Here are snippet:
use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Backend\App\Action; protected $_fileUploaderFactory; public function __construct( \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory, Action\Context $context ) { $this->_fileUploaderFactory = $fileUploaderFactory; parent::__construct($context); } public function execute(){ $uploader = $this->_fileUploaderFactory->create(['fileId' => 'image']); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $uploader->setAllowRenameFiles(false); $uploader->setFilesDispersion(false); $path = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA) ->getAbsolutePath('images/'); $uploader->save($path); }
Kindly refer this code and add file upload functionality for product or giftcard.