1

This question is an exact duplicate of:

I have created form and it has a image uploading field but the image is not saved in db app/code/Dyode/Pricebeat/Controller/User/Post.php

 <?php
  namespace Dyode\Pricebeat\Controller\User;
  use Magento\Framework\App\Action\Action;
  use Magento\Framework\App\Action\Context;
  use Dyode\Pricebeat\Model\FormFactory;
  use Magento\Framework\View\Result\PageFactory;
  use Magento\Framework\Exception\LocalizedException;
  use Magento\Framework\Session\SessionManagerInterface;
  use Magento\Framework\HTTP\PhpEnvironment\Request;
  use \Magento\Framework\App\RequestInterface;
  use Magento\Framework\App\Request\Http;
  use \Dyode\Pricebeat\Model\Upload;
  use \Magento\Framework\Filesystem;
  use \Magento\MediaStorage\Model\File\UploaderFactory;

    class Post extends Action
 {
   protected $_modelFormFactory;
protected $resultPageFactory;
protected $_sessionManager;
protected $uploadModel;
protected  $filesystem;
protected $fileUploaderFactory;



public function __construct(
  Context $context,
  FormFactory $modelFormFactory,
  PageFactory $pageFactory,
  SessionManagerInterface $sessionManager)
{
    $this->resultPageFactory = $pageFactory;
    $this->_modelFormFactory = $modelFormFactory;
    $this->_sessionManager = $sessionManager;
    parent::__construct($context);
}

public function execute()
{
    $this->validatedParams();
    $this->getFormData();

    echo "hello from the controller";
    exit();
}

private function validatedParams()
{
    $request = $this->getRequest();
    if (trim($request->getParam('first_name')) === '') {
        throw new LocalizedException(__('First Name is missing'));
    }

    if (trim($request->getParam('last_name')) === '') {
        throw new LocalizedException(__('Last Name is missing'));
    }

    if (false === \strpos($request->getParam('email'), '@')) {
        throw new LocalizedException(__('Invalid email address'));
    }
    if (trim($request->getParam('phonenumber')) === '') {
        throw new LocalizedException(__('Phone Number is missing'));
    }
    if (trim($request->getParam('account_number')) === '') {
        throw new LocalizedException(__('Account Number is missing'));
    }
    if (trim($request->getParam('invoice_number')) === '') {
        throw new LocalizedException(__('Invoice Number is missing'));
    }
    if (trim($request->getParam('product_url')) === '') {
        throw new LocalizedException(__('product url Number is missing'));
    }
    if (trim($request->getParam('product_image_url')) !== '') {
        throw new LocalizedException(__('image is missing'));
    }

    //Add your more validations here
    return $request->getParams();
}
private function getFormData()
{

   $resultRedirect     = $this->resultRedirectFactory->create();
   $FormModel          = $this->_modelFormFactory->create();
   $data               = $this->getRequest()->getPost();
   $filedata           =$this->getRequest()->getFiles('product_image_url');

   if (!empty($_FILES[$product_image_url]['name'])) {
try {
    $uploader = $this->_uploaderFactory->create(['fileId' => $product_image_url]);
    $uploader->setAllowedExtensions(['jpg','jpeg','gif','png']);
    $uploader->setAllowRenameFiles(true);
    $uploader->setFilesDispersion(false);
    $_FILES[product_image_url]['name'] = str_replace(' ', '-', $_FILES[$product_image_url]['name']);
    $path = $this->_getUploadPath();
    $uploader->save($path, $_FILES[$product_image_url]['name']);
    $this->_myModel->setData(
        $field,
        "manufacturer/".$uploader->getUploadedFileName()
    );
} catch (\Exception $e) {
    $this->messageManager->addSuccess($e->getMessage());
    }
  } else {
     unset($_FILES[product_image_url]);
   //Removing it from data set as no new
   //file was uploaded (fix for edit action)
   $this->_myModel->unsetData($product_image_url);
    }
     // echo "<pre>";
      // var_dump( $filedata);
      // exit();
      $date               = date('Y-m-d h:i:sa');

   $FormModel->setData('first_name', $data['first_name']);
   $FormModel->setData('last_name', $data['last_name']);
   $FormModel->setData('email', $data['email']);
   $FormModel->setData('phonenumber', $data['phonenumber']);
   $FormModel->setData('account_number', $data['account_number']);
   $FormModel->setData('invoice_number', $data['invoice_number']);
   $FormModel->setData('product_url', $data['product_url']);
   $FormModel->setData('product_image_url', $data['product_image_url']);



   $FormModel->setData('product_image_url', $filedata);
   $FormModel->setData('created_date', $date);
   $FormModel->setData('status', $data['status']);

   $FormModel->save();

   $this->_redirect('blog/index');
   $this->messageManager->addSuccess(__('The data has been saved.'));
}
}

app/code/Dyode/Pricebeat/Model/Upload.php

<?php

namespace Dyode\Pricebeat\Model;

 class Upload
 {
  /**
 * Upload model factory
 *
 * @var \Magento\MediaStorage\Model\File\UploaderFactory
 */
protected $uploaderFactory;

/**
 * constructor
 *
 * @param \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
 */
public function __construct(
    \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
)
{
    $this->uploaderFactory = $uploaderFactory;
}

/**
 * upload file
 *
 * @param $input
 * @param $destinationFolder
 * @param $data
 * @return string
 * @throws \Magento\Framework\Exception\LocalizedException
 */
public function uploadFileAndGetName($input, $destinationFolder, $data)
{
    try {
        if (isset($data[$input]['delete'])) {
            return '';
        } else {
            $uploader = $this->uploaderFactory->create(['fileId' => $input]);
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            $uploader->setAllowCreateFolders(true);
            $result = $uploader->save($destinationFolder);
            return $result['file'];
        }
    } catch (\Exception $e) {
        if ($e->getCode() != \Magento\Framework\File\Uploader::TMP_NAME_EMPTY) {
            throw new \Magento\Framework\Exception\LocalizedException($e->getMessage());
        } else {
            if (isset($data[$input]['value'])) {
                return $data[$input]['value'];
            }
        }
    }
    return '';
}
}

marked as duplicate by Amit Bera Sep 18 '18 at 10:12

This question was marked as an exact duplicate of an existing question.

  • what is $product_image_url for you did not define in that controller ? – Ansar Husain Sep 18 '18 at 9:57
  • You should replace $product_image_url to "product_image_url" here – Ansar Husain Sep 18 '18 at 9:59
1

Please try below code to upload attachment.

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace <vendor>\<modulename>\Controller\<controller name>;

use \Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
/**
 * Description of CreatePost
 *
 * @author dharmendra
 */
class CreatePost extends \Magento\Customer\Controller\AbstractAccount
{

    /**
     * @var \Magento\Framework\Filesystem
     */
    private $fileSystem;

    /**
     * @var \Magento\Customer\Model\Session
     */
    private $customerSession;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\Filesystem $fileSystem)
    {
        parent::__construct($context);
        $this->customerSession = $customerSession;
        $this->fileSystem = $fileSystem;
    }

    public function execute() {
        $data = $this->getRequest()->getPostValue();
        if ($data) {

            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

            $model = $this->_objectManager->create('<vendor>\<module>\Model\<modlename>');

            $data['status'] = 1;

            if ($_FILES['attachments']['name']) {
                try {
                    $uploader = $this->_objectManager->create(
                        'Magento\MediaStorage\Model\File\Uploader',
                        ['fileId' => 'attachments']
                    );
                    //$uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                    $uploader->setAllowRenameFiles(true);
                    $uploader->setFilesDispersion(true);

                    $mediaDirectory = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA);
                    $path = $mediaDirectory->getAbsolutePath('images/');
                    $imagePath = $uploader->save($path);
                    $data['attachments'] = $imagePath['file'];
                } catch (Exception $e) {
                    $this->messageManager->addException($e->getMessage());
                    return $resultRedirect->setUrl($this->_redirect->getRefererUrl()); 
                }
            }

            $model->setData($data);

            try {                
                $model->save();
                $this->messageManager->addSuccess(__('Your message'));
                return $resultRedirect->setPath('helpdesk/ticket/tickets/');
            } catch (\Exception $e) {
                $this->messageManager->addException($e->getMessage());
            }
            return $resultRedirect->setUrl($this->_redirect->getRefererUrl());
        } else {
            $this->messageManager->addError(__('Invalid request. Please contact administrator.'));
        }
        return $resultRedirect->setUrl($this->_redirect->getRefererUrl());        
    }
}

Model file.

<?php
namespace <vendor>\<moduleName>\Model;

class <modelName> extends \Magento\Framework\Model\AbstractModel
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('<vendor>\<moduleName>\Model\ResourceModel\<resourcemodelname>');
    }
}
?>

Resource Model.php

<?php
namespace <vendor>\<modulname>\Model\ResourceModel;

class <resoursemodelname> extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('<tablename>', 'id');
    }
}
?>

Still any problem let me know.

  • $model = $this->_objectManager->create('<vendor>\<module>\Model\<modlename>'); – Nismath vi Sep 18 '18 at 10:17
  • i'm not write any model – Nismath vi Sep 18 '18 at 10:18
  • If you have to save data in db than you have to create model for that. – Dharmendra Jadav Sep 18 '18 at 10:19
  • I have added a mode can you please check is that correct? – Nismath vi Sep 18 '18 at 10:23
  • Not like this you have to create table for this and you have add create model like this which i add. please check. – Dharmendra Jadav Sep 18 '18 at 10:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.