Question

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.")
    );
}
Was it helpful?

Solution

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());
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top