Magento 2 – File Upload Form in Custom Module Frontend

extensionsfile uploadmagento2

I am getting this error when I submit the form from the front end. Although I set the required extension in the setAllowedExtensions

Exception #0 (InvalidArgumentException): Disallowed file type.

if($files!='')
    {
        foreach ($files as $key => $value) {

            $uploaderFactory = $this->uploaderFactory->create(['fileId' => $key]);
            $uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png','pdf', 'docx', 'doc']);
            $imageAdapter = $this->adapterFactory->create();
            /* start of validated image */
            $uploaderFactory->addValidateCallback('custom_image_upload',
                $imageAdapter,'validateUploadFile');
            $uploaderFactory->setAllowRenameFiles(true);
            $uploaderFactory->setFilesDispersion(true);
            $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
            $destinationPath = $mediaDirectory->getAbsolutePath('custom_module');
            $result = $uploaderFactory->save($destinationPath);

            $imagepath = $result['file'];
            //print_r($imagepath);exit;

            $saveData['custom_file'] = $imagepath;
            //$this->model->setData($saveData);

            //$submitModel->setData($saveData);
            //$submitModel->save();
        }
    }

When I upload a jpeg or png it works fine ,but gives error on doc,docx and pdf

Best Answer

The problem with following code

$uploaderFactory->addValidateCallback('custom_image_upload',
                $imageAdapter,'validateUploadFile');

You are using the Image Adapter factory that will not allow you upload the files. You can use File Uploader instead.

Magento\Framework\File\Uploader
Related Topic