skip to Main Content

I have a problem uploading a file can you help me? when I upload a smaller file it runs smoothly but when I upload a larger file it’s problematic, does anyone know the solution? this is the controller part:

$title = $this->request->getPost('title');
$kategori = $this->request->getPost('kategori');
$seo = str_replace(" ", "-", strtolower($kategori));
$deskripsi = $this->request->getPost('deskripsi');
$data=array();
$file = $this->request->getFile('imagefile');
$data=array();
if ($file->getSize() > 0){
  $image=$file->getRandomName();
  $file->move('./uploads/peta/',$image);
  $data = array(
    'title'     => $title,
    'kategori'  => $kategori,
    'seo'       => $seo,
    'deskripsi' => $deskripsi,
    'file'      => $image
  );
}else{
  $data = array(
    'title'     => $title,
    'kategori'  => $kategori,
    'seo'       => $seo,
    'deskripsi' => $deskripsi
  );
}

2

Answers


  1. You need to check if the file is set before trying to call file methods. It seems that the file isn’t being sent over your request. As you said, it works with smaller files so please check the php.ini file to see your max_upload_size settings and post_max_size settings. Change the maximum upload file size

    Otherwise, to ensure your code won’t fail on posts, you can do this:

    if (!empty($file) && $file->getSize() > 0){
      $image=$file->getRandomName();
      $file->move('./uploads/peta/',$image);
      $data = array(
        'title'     => $title,
        'kategori'  => $kategori,
        'seo'       => $seo,
        'deskripsi' => $deskripsi,
        'file'      => $image
      );
    }else{
      $data = array(
        'title'     => $title,
        'kategori'  => $kategori,
        'seo'       => $seo,
        'deskripsi' => $deskripsi
      );
    }
    

    This will check if there is a file before trying to use it.

    Login or Signup to reply.
  2. Use $files->hasFile('') to check whether file exist. And then check other file properties as mentioned below.

    $files = $this->request->getFiles();
    
    if ($files->hasFile('imagefile'))
    {
        $file = $files->getFile('imagefile');
    
        // Generate a new secure name
        $name = $file->getRandomName();
    
        // Move the file to it's new home
        $file->move('/path/to/dir', $name);
    
        echo $file->getSize();      // 1.23
        echo $file->getExtension();     // jpg
        echo $file->getType();          // image/jpg
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search