7

I am current working on a file upload functionality in Magento. Everthing is working great.

I am using the \Magento\Framework\File\Uploader and files are getting properly uploaded.

The issue I would like to check if the file has been uploaded by the user before I initialize the Uploader class.

Currently I am doing is like:

if (!empty($_FILES[$field]['name'])) {
    try {
        $uploader = $this->_uploaderFactory->create(['fileId' => $field]);
        $uploader->setAllowedExtensions(['jpg','jpeg','gif','png']);
        $uploader->setAllowRenameFiles(true);
        $uploader->setFilesDispersion(false);
        $_FILES[$field]['name'] = str_replace(' ', '-', $_FILES[$field]['name']);
        $path = $this->_getUploadPath();
        $uploader->save($path, $_FILES[$field]['name']);
        $this->_myModel->setData(
            $field,
            "manufacturer/".$uploader->getUploadedFileName()
        );
    } catch (\Exception $e) {
        $this->messageManager->addSuccess($e->getMessage());
    }
} else {
    unset($_FILES[$field]);
    //Removing it from data set as no new
    //file was uploaded (fix for edit action)
    $this->_myModel->unsetData($field);
}

I would like to know if there is a better way to access $_FILES super global using the framework request object by using something like ?

$this->getRequest()->getFiles()

instead of accessing it directly which I think might be a bad practice to follow.

I tried to search this in the codebase but didn't get anything relevant.

I am more interested in learning how we may access the $_FILES super global the magento way by using the magento Request object not how the proper way of uploading files

0

1 Answer 1

12

I also encountered this problem before. Using global variable $_FILES is bad way. Moreover you cannot place module with using of global variables on marketplace. (SuperglobalSniff in Magento EQP)

In RequestInterface there are no any methods for getting files. But in implementation of RequestInterface there is method getFiles(), which return requested files data array.

In sum:

I use type casting \Magento\Framework\App\RequestInterface to Magento\Framework\App\Request\Http and fetch files using getFiles method.

2
  • 1
    Can you please share sample code for this? Oct 27, 2017 at 7:49
  • 1
    @SaiidatRLTSquare in action $files = $this->getRequest()->getFiles()
    – Max
    Oct 29, 2017 at 8:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.