3

I want to copy pdf file from one folder
i.e /pub/media/xyz to another /pub/media/abc programmatically.
And create target folder if does not exist.

2 Answers 2

5

I used the function copyFile() from Magento\Framework\Filesystem;

  use Magento\Framework\Filesystem;
  public function __construct(
        Filesystem $filesystem
    ) {
        $this->mediaDirectory = $filesystem->getDirectoryWrite('media');
    }
    
    $result = $this->mediaDirectory->copyFile(
        $this->getPath(self::TMP_SUBDIR, $filename),
        $this->getPath($subdirToSave, $filename)
    );
8
  • exception throws Class module\modulename\Controller\Vendors\Import\File does not exist in [module\modulename\Controller\Vendors\Import\Run\Interceptor] Jan 28, 2019 at 11:59
  • Please, run 'rm -rf generated/" and try again Jan 28, 2019 at 12:01
  • already run this command Jan 28, 2019 at 12:02
  • can you help me with object manager temporary ? Jan 28, 2019 at 12:15
  • @kimnana, There is a typo mistake. use Filesystem $backendFile instead of File $backendFile Jan 28, 2019 at 12:22
1

You can use cp() function of class Magento\Framework\Filesystem\Io\File

 protected $_fileSystem;

    public function __construct(
        \Magento\Framework\Filesystem\Io\File $filesystemIo
    ) {
        $this->filesystemIo = $filesystemIo;
    }

    public function execute(){
    $filePath  = '/var/www/html/pub/media/imagesName.jpg';//source file
    $copyFileFullPath  = '/var/www/html/pub/media/folderName/newImagesName.jpg'; // destination file

    $filePath = $this->filesystemIo->cp($filePath, $copyFileFullPath);
}
3
  • actually , I tried this code at morning . but this doesn't worked. Jan 28, 2019 at 13:09
  • @kimnana, there is one typo mistake please make it correct $this->filesystemIo->cp. I have checked and its working fine at my end Jan 29, 2019 at 5:45
  • @AmitNaraniwal, what if already file exist in destination directory?
    – Manjunath
    Apr 7 at 14:17

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.