How to upload image in frontend side of typo3 extension development


Here from a form to upload a small controller function into extbase images:

Whenever we upload image from frontend side that every time we must need to check image is exist or not. if image is exists then we need to rename image with unique name.

Following code will help you for how to image upload from frontend side with clean file name

<?php

  // check the form is submit
  if ($this->request->hasArgument('submit')){
    
    // Get all submitted post data 
    $userData = $this->request->getArguments();

    // media is stand for your file name [ you will get data of image]

    $file['name']    = $userData['media']['name'];
    $file['type']    = $userData['media']['type'];
    $file['tmp_name']  = $userData['media']['tmp_name'];
    $file['size']    = $userData['media']['size'];

    // Store the image file
    $files = $this->uploadFile($file['name'], $file['type'], $file['tmp_name'], $file['size']);  
  }


  /**
   * uploadFile
   * @param $name
   * @param $type
   * @param $temp
   * @param $size
   * @return
  */
    
  protected function uploadFile($name, $type, $temp, $size) {
    
    if($size > 0) {
      $basicFileFunctions = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('t3lib_basicFileFunctions');
      
      // upload folder path
      $uploadPath = 'fileadmin/user_upload/jainish';
      
      $name = $basicFileFunctions->cleanFileName($name);
      $uploadPath = $basicFileFunctions->cleanDirectoryName($uploadPath);
      $uniqueFileName = $basicFileFunctions->getUniqueName($name, $uploadPath);
      $fileStored = move_uploaded_file($temp, $uniqueFileName);
      
      $returnValue = basename($uniqueFileName);
    }
    
    return $returnValue;
  }
?>

I hope above code will work for you and made your day ๐Ÿ˜‰ enjoy ๐Ÿ™‚

If you have any queries, please do not hesitate to contact me at Jainish Senjaliya

Leave a comment