在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()
在文件名中查找字符串。