2

I successfully uploaded the file using this code:

public function execute()
{
    /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultRedirectFactory->create();
    try{
        $target = $this->_mediaDirectory->getAbsolutePath('mycustomfolder/');        
        /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
        $uploader = $this->_fileUploaderFactory->create(['fileId' => 'file']);
        /** Allowed extension types */
        $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png', 'zip', 'doc']);
        /** rename file name if already exists */
        $uploader->setAllowRenameFiles(true);
        /** upload file in folder "mycustomfolder" */
        $result = $uploader->save($target);
        if ($result['file']) {
            $this->messageManager->addSuccess(__('File has been successfully uploaded')); 
        }
    } catch (\Exception $e) {
        $this->messageManager->addError($e->getMessage());
    }
    return $this->resultRedirectFactory->create()->setPath(
        '*/*/upload', ['_secure'=>$this->getRequest()->isSecure()]
    );            
}

the problem is I need to rename the file name if I found a specific string in that file name, is there a way to do this?

6

The method $uploader->save($target); has a second parameter: string $newFileName

Also you'll find the method $uploader->getUploadedFileName() to get the filename.

You can use strpos() to find the string in the file name.

I hope it helps you.

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.