I am trying to upload a file, but getting error every time - The file was not uploaded
Steps that I am following -
Html -
<div class="field npwp_attachment" id="npwp-attachment-div">
<label class="label" for="npwp_attachment">
<span><?= $block->escapeHtml(__('Attach NPWP – Company')) ?></span>
</label>
<div class="control">
<input name="company[npwp_attachment]" id="npwp_attachment" title="<?php $block->escapeHtmlAttr(__('Attach NPWP – Company')) ?>" class="input-file" type="file" >
</div>
</div>
In Model -
use Magento\Framework\App\Filesystem\DirectoryList;
protected $uploaderFactory;
protected $adapterFactory;
protected $filesystem;
public function __construct(
\Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
\Magento\Framework\Image\AdapterFactory $adapterFactory,
\Magento\Framework\Filesystem $filesystem
){
$this->uploaderFactory = $uploaderFactory;
$this->adapterFactory = $adapterFactory;
$this->filesystem = $filesystem;
}
$uploaderFactory = $this->uploaderFactory->create(['fileId' => 'npwp_attachment']);
$uploaderFactory->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
$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_image');
echo $destinationPath;exit;
$result = $uploaderFactory->save($destinationPath);
if (!$result) {
throw new LocalizedException(
__('File cannot be saved to path: $1', $destinationPath)
);
}
In model, I have also printed $_FILES and this is the response -
Array
(
[company] => Array
(
[name] => Array
(
[npwp_attachment] => Untitled Diagram.jpg
)
[type] => Array
(
[npwp_attachment] => image/jpeg
)
[tmp_name] => Array
(
[npwp_attachment] => /tmp/phpOtC07v
)
[error] => Array
(
[npwp_attachment] => 0
)
[size] => Array
(
[npwp_attachment] => 153369
)
)
)
Findings till now -
I have figured out that their is some issue with tmp_name, this error is coming form -
vendor/magento/framework/File/Uploader.php
if (!file_exists($this->_file['tmp_name'])) {
$code = empty($this->_file['tmp_name']) ? self::TMP_NAME_EMPTY : 0;
throw new \DomainException('The file was not uploaded.', $code);
}
I have also printed $this->_file['tmp_name'], and this is empty.
I am getting error in this line -
$uploaderFactory = $this->uploaderFactory->create(['fileId' => 'npwp_attachment']);
Any idea what is the issue and how this can be fixed ??
Thanks.