0

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.

3
  • Have you tried anything for save? Commented May 26, 2017 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
    Commented May 26, 2017 at 5:21
  • pleade share your code which you have tried. Commented May 26, 2017 at 5:28

1 Answer 1

1

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

In script, write this code

<script>
    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++)
        {
            uploadFile(files[i],up_id,upremv_id);
        }
    }
    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) {
                jQuery('#imgna'+up_id).val(xhr.responseText);
                console.log(xhr.responseText); // handle response.
                jQuery('#'+up_id).remove();
                jQuery('#'+upremv_id).remove();
                var img_va = '<img class="image" src="<?php echo $mediaUrl.'custom/'?>'+xhr.responseText+'">';
                jQuery('#pre'+up_id).html(img_va);
            }
        };
        fd.append('uploaded_file', file);

</script>

Then, in your custom controller,

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

public function __construct(\Magento\Framework\App\Action\Context $context)
{
    parent::__construct($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'];
    $file_type=$_FILES['uploaded_file']['type'];

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

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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