Created a custom tab on admin product edit page. Here added a image upload section. I need to save the uploaded image to a folder.
1 Answer
By using jquery, we can save the image to a folder.
In script, write this code
<script>
function file_up(id)
{
var up_id = 'uploadfiles'+id;
var upremv_id = 'upload'+id;
var files = document.getElementById(up_id).files;
for (var i = 0; i < files.length; i++)
{
uploadFile(files[i],up_id,upremv_id);
}
}
function uploadFile(file,up_id,upremv_id){
var url = "<?php echo $baseurl ?>helloworld/index/upload";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
jQuery('#imgna'+up_id).val(xhr.responseText);
console.log(xhr.responseText); // handle response.
jQuery('#'+up_id).remove();
jQuery('#'+upremv_id).remove();
var img_va = '<img class="image" src="<?php echo $mediaUrl.'custom/'?>'+xhr.responseText+'">';
jQuery('#pre'+up_id).html(img_va);
}
};
fd.append('uploaded_file', file);
</script>
Then, in your custom controller:
Class Upload extends \Magento\Framework\App\Action\Action
{
public function __construct(\Magento\Framework\App\Action\Context $context)
{
parent::__construct($context);
}
public function execute()
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$fileSystem = $objectManager->create('\Magento\Framework\Filesystem');
$mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA)->getAbsolutePath();
$media = $mediaPath . 'custom/';
// exit;
$file_name = rand() . $_FILES['uploaded_file']['name'];
$file_size = $_FILES['uploaded_file']['size'];
$file_tmp = $_FILES['uploaded_file']['tmp_name'];
$file_type = $_FILES['uploaded_file']['type'];
if (move_uploaded_file($file_tmp, $media . $file_name)) {
echo $file_name;
} else {
echo "File was not uploaded";
}
}
}