Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File upload form for custom Joomla component

I have a field in my form which is of type file. When the user clicks on the save icon, I want to naturally upload the file to the server and save the filename in the database. I tried testing this out by echoing the filename but it doesn't seem to be working. Also, how do I add the filename to the database? Is it done in the model? Thanks!

controllers/customcom.php

jimport('joomla.filesystem.file');     
class CustomComControllerCustomCom extends JControllerForm
        {
            function save()
            {
                $file = JRequest::getVar('img_url', null, 'files', 'array');

                $filename = JFile::makeSafe($file['name']);

                echo $filename;
                }
        }

models/forms/customcom.xml

    <?xml version="1.0" encoding="utf-8"?>
    <form enctype="multipart/form-data">
            <fieldset>
                  <field
                        name="img_url"
                        type="file"
                        label="Image upload"
                        description=""
                        size="40"
                        class="inputbox"
                        default=""
                />
            </fieldset>
   </form>
like image 448
Moo33 Avatar asked Mar 27 '13 07:03

Moo33


2 Answers

Just figured it out.

The correct way is

$jinput = JFactory::getApplication()->input;
$files = $jinput->files->get('jform');
$file = $files['img_url'];

That should do the trick. The $file array then holds the following keys:

  • error
  • name
  • size
  • tmp_name
  • type

I've deleted my original answer as it was misleading.

like image 196
Bakual Avatar answered Nov 02 '22 16:11

Bakual


Get inspired by Media manager:

  • MediaControllerFile
  • MediaHelper::canUpload

Just note that this component is quite old (refactoring is in preparations)

// Import dependencies
jimport('joomla.filesystem.file')

// Get input
$input = JFactory::getApplication()->input;

// Get uploaded file info
$file_info = $input->files->get('img_url', null);

// This will hold error
$error = null;

// Check if there was upload at all, mime is correct, file size, XSS, whatever...
if (!MycomponentHelper::canUpload($file_info, $error)
{
    $this->setError('problem: ' . $error);
    return false;
}

// Move uploaded file destination
JFile::upload($file_info['tmp_name'], $destination);
like image 34
piotr_cz Avatar answered Nov 02 '22 17:11

piotr_cz