1

How can I change the name of the file being upload (will be changed to something random)? I can't find any docs for this and similar questions either focus on the wrong bit or are for Magento 1.

This script does work without attempting to change the name - the file is uploaded to $desintationPath (which is in the /pub directory).

try {
    $uploader = $this->uploaderFactory->create(['fileId' => 'file'])
        ->setAllowCreateFolders(true)
        ->setAllowedExtensions($this->allowedExtensions)
        ->addValidateCallback('validate', $this, 'validateFile');
    if (!$uploader->save($destinationPath)) {
        throw new LocalizedException(
            __('File cannot be saved to path: $1', $destinationPath)
        );
    }
} catch (\Exception $e) {
    $this->messageManager->addError(
        __("Sorry we encountered a problem. Please try again or get in touch.")
    );
}
3

You can pass your custom file name in save function as second argument. If you check vendor\magento\framework\File\Uploader.php::save($destinationFolder, $newFileName = null) You find second argument is the new file name with which you want to save.

All you have to do is

$uploader->save($destinationPath,YOUR_RANDOM_FILENAME);

And your file will be stored with the name you pass.

To Upload file with extension, use below code.

$uploader->save($destinationPath,YOUR_RANDOM_FILENAME.'.'.$uploader->getFileExtension());
  • @jaiminsutariya how to save it with the file extension? – simple guy May 2 '18 at 5:18
  • @simpleguy, please check updated answer for the same. – Jaimin Sutariya May 2 '18 at 8:45

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.