The base for file handling is the JFile class.
First, you need to add the attribute enctype="multipart/form-data" to the form. Otherwise, you are unable to upload a file.
<form name="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload" />
<input type="submit" />
To retrieve file details from uploaded file, sent from upload form:
$input = JFactory::getApplication()->input;
$file = $input->files->get('file_upload');
The variable $file is an array. After getting the file, you can access its details:
To clean up filename to get rid of strange characters and spaces:
$filename = JFile::makeSafe($file['name']);
Just feed the function with a filename and it will return the extension of the file you selected.
$ext = JFile::getExt($filename);
To check if the file has the right extension, for example, jpg only
if (strtolower(JFile::getExt($filename)) == 'jpg')
To strip the file extension and return the filename without the extension:
$name = JFile::stripExt($filename);
The function also checks availability and permissions on both source and destination path.
// Set up the source and destination of the file
$src = $file['tmp_name'];
$dest = JPATH_COMPONENT . "/uploads/" . $filename;
if (JFile::upload($src, $dest))
$this->setMessage('File is uploaded');
$this->setMessage('File is not uploaded');
This function also checks if the file you want to copy exists and the destination really is available.
The function tries to delete the file, making sure it is actually existing. It also checks permissions. If permissions are not set up properly, it tries to change them and delete the file.