You can save any file type to custom folder location using Magento 2.
If you are working with image, pdf or CSV file and you want to save the file to a specific location using Magento standard way, You have to add a dependency to your __construct function.
The move_uploaded_file() function moves an uploaded file to a new location using core PHP but you can do it Using Magento standard way.
Magento\Framework\Filesystem
Magento\MediaStorage\Model\File\UploaderFactory
Both the class used to save the file to a specific location.
Your phtml file contains input type file,
<input id=”filename” name=”filename” class=”input-file required” type=”file” aria-required=”true”>
From server end, you just need to do below code to save your any custom file to folder,
I have given demo for Save CSV or Image to var/importexport folder using Block file.
<?php namespace Rbj\ImageSave\Block; use Magento\Framework\App\Filesystem\DirectoryList; class Demo extends \Magento\Framework\View\Element\Template { public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\Filesystem $filesystem, \Magento\MediaStorage\Model\File\UploaderFactory $_uploaderFactory, array $data = [] ) { $this->_uploaderFactory = $_uploaderFactory; $this->_varDirectory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); parent::__construct($context,$data); } /** * Save Image or CSV file to var/importexport folder */ public function saveFile() { if(isset($_FILES['filename']['name'])) { $uploader = $this->_uploaderFactory->create(['fileId' => 'filename']); $workingDir = $this->_varDirectory->getAbsolutePath('importexport/'); $result = $uploader->save($workingDir); } }
In the above Block file, fileId is your input file name attribute.
Once you can run the above code, your file will be saved inside,
var/importexport/files.jpg or var/importexport/files.csv