Magento2 如何上传文件

在Mamgento2中,我写了个控制器用于上传文件,并且获取到上传文件后如何重命名文件

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()]
    );            
}

如何重命名呢

该方法$uploader->save($target);具有第二个参数:字符串$ newFileName

或者找到$uploader->getUploadedFileName()获取文件名的方法。

或者可以用strpos()在文件名中查找字符串。

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
最旧
最新 最多投票
内联反馈
查看所有评论