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.
Hi @Musammil,
To add a file upload feature to the Gift Message form in Magento 2 and ensure the uploaded file is stored and its URL is saved in the Gift Message table.
Please follow the below steps.
Step 1: Add File Input to the Gift Message Form
First, add a file input element to your gift-message-form.html.
app/design/frontend/YourVendor/YourTheme/Magento_GiftMessage/templates/gift-message-form.html:
<!-- Add the file input to the gift message form --> <input type="file" id="gift-message-image" name="gift-message-image" data-bind="attr: {name: 'gift-message-image'}" />
Create a custom module to handle the file upload. Let's name it Vendor_GiftMessage.
Create all the necessary files for the module. and then create a controller at app/code/Vendor/GiftMessage/Controller/Upload/Image.php
<?php namespace Vendor\GiftMessage\Controller\Upload; use Magento\Framework\App\Action\Context; use Magento\Framework\Controller\Result\JsonFactory; use Magento\MediaStorage\Model\File\UploaderFactory; use Magento\Framework\Filesystem; use Magento\Framework\App\Filesystem\DirectoryList; class Image extends \Magento\Framework\App\Action\Action { protected $resultJsonFactory; protected $uploaderFactory; protected $filesystem; public function __construct( Context $context, JsonFactory $resultJsonFactory, UploaderFactory $uploaderFactory, Filesystem $filesystem ) { $this->resultJsonFactory = $resultJsonFactory; $this->uploaderFactory = $uploaderFactory; $this->filesystem = $filesystem; parent::__construct($context); } public function execute() { $result = $this->resultJsonFactory->create(); try { $uploader = $this->uploaderFactory->create(['fileId' => 'gift-message-image']); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(false); $mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA); $result = $uploader->save($mediaDirectory->getAbsolutePath('giftmessage')); if (!$result) { throw new \Exception('File cannot be saved to the destination folder.'); } $imageUrl = 'giftmessage/' . $result['file']; return $result->setData(['success' => true, 'image_url' => $imageUrl]); } catch (\Exception $e) { return $result->setData(['success' => false, 'message' => $e->getMessage()]); } } }
Modify your JavaScript to handle the file upload via AJAX and update the gift message.
app/design/frontend/YourVendor/YourTheme/web/js/gift-message.js:
define([ 'jquery', 'Magento_Customer/js/customer-data', 'mage/translate' ], function ($, customerData, $t) { 'use strict'; return function (config) { $('#gift-message-image').on('change', function () { var formData = new FormData(); formData.append('gift-message-image', $('#gift-message-image')[0].files[0]); $.ajax({ url: '/giftmessage/upload/image', type: 'POST', data: formData, contentType: false, processData: false, success: function (response) { if (response.success) { // Update the gift message form with the image URL var imageUrl = response.image_url; // Assuming you have a hidden input to store the image URL $('input[name="gift-message[image_url]"]').val(imageUrl); // Trigger the gift message API update here updateGiftMessage(imageUrl); } else { alert($t('File upload failed: ') + response.message); } } }); }); function updateGiftMessage(imageUrl) { var giftMessageData = { 'gift_message': { 'image_url': imageUrl, // other gift message data } }; $.ajax({ url: '/carts/mine/gift-message', type: 'POST', contentType: 'application/json', data: JSON.stringify(giftMessageData), success: function (response) { // handle success }, error: function (xhr, status, error) { // handle error } }); } }; });
Include the JS in Your Layout:
app/design/frontend/YourVendor/YourTheme/Magento_GiftMessage/layout/default.xml:
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <head> <script src="js/gift-message.js"/> </head> </page>
Ensure the Gift Message API can handle the new image_url field. You might need to extend the functionality of the Gift Message model and resource model to save this data.
With these steps, you have added a file upload feature to the Gift Message form, created an AJAX controller to handle the file upload, and modified the JavaScript to send the uploaded file URL to the Gift Message API.
If the issue will be resolved, Click Kudos & Accept as a Solution.