I have added a custom tab on admin product edit page. And in that custom tab added a image upload field. I need to save the image while saveing the product.

Is it possible to do it via ajax and a controller?

Please give me a solution to save image.

  • Have you tried anything for save? – Rakesh Jesadiya May 26 '17 at 4:52
  • i wrote a ajax to call a controller. But how to pass image details to that controller and on execute function what to write for the saving image – Rita Jose May 26 '17 at 5:21
  • pleade share your code which you have tried. – Rakesh Jesadiya May 26 '17 at 5:28

By using jquery, we can save the image to a folder.

In script, write this code

    function file_up(id)
        var up_id = 'uploadfiles'+id;
        var upremv_id = 'upload'+id;
        var files = document.getElementById(up_id).files;
        for (var i = 0; i < files.length; i++)
    function uploadFile(file,up_id,upremv_id){
        var url = "<?php echo $baseurl ?>helloworld/index/upload";
        var xhr = new XMLHttpRequest();
        var fd = new FormData();
        xhr.open("POST", url, true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText); // handle response.
                var img_va = '<img class="image" src="<?php echo $mediaUrl.'custom/'?>'+xhr.responseText+'">';
        fd.append('uploaded_file', file);


Then, in your custom controller,

Class Upload extends \Magento\Framework\App\Action\Action {

public function __construct(\Magento\Framework\App\Action\Context $context)
public function execute()
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    $fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
    $mediaPath  =   $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();
    $media  =  $mediaPath.'custom/' ;

  //  exit;

    $file_name = rand().$_FILES['uploaded_file']['name'];
    $file_size =$_FILES['uploaded_file']['size'];
    $file_tmp =$_FILES['uploaded_file']['tmp_name'];

    if (move_uploaded_file($file_tmp,$media.$file_name))
        echo $file_name;
        echo "File was not uploaded";


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.