1

I recently added my own form to the Magento frontend. The form contains a file type input, an used the file uploader class to save the file. But I was wondering how save this class is?

I already changed the name, checked the file size (not in code below) and checked the file extension. But I'm wondering if that is enough.

Here is my code (I'm checking file size in an earlier function):

private function uploadFile($id) {
    $uploader = $this->_fileUploaderFactory->create(['fileId' => $id]);
    $uploader->setAllowRenameFiles(TRUE);
    $uploader->setFilesDispersion(TRUE);
    $uploader->setAllowCreateFolders(TRUE);
    $uploader->setAllowedExtensions(Helper::ALLOWED_FILE_UPLOADS);

    $path = $this->_fileSystem->getDirectoryRead(DirectoryList::VAR_DIR)
      ->getAbsolutePath();

    $uploader->save($path . '/myfiles', $id . '.' . $uploader->getFileExtension());

    return '/myfiles' . $uploader->getUploadedFileName();
  }
-1

Please check with below 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()]
    );            
}

I hope its very helpful to you.

  • I know how to upload files / images, my question was how secure is it? I know there can be weird pdf files that execute som php code. – Arno Vande Cappelle Aug 5 at 10:18

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.