Hello friends,
Today we will learn how to upload a file in Joomla. In Joomla, upload() function is used to upload a file from source to destination. This function is similar to PHP move_uploaded_file() function.
Syntax:
JFile::upload($src, $dest);
In above syntax, JFile is the class in which upload() function is defined. It is a pre-defined function. $src is the source of the file and $dest is the destination where we will upload the file.
Let's take an example to understand this.
Suppose we have a form with a input field of type file as follows:
<form name="upload" method="post" enctype="multipart/form-data">
<input type="file" name="fileupload" />
<input type="submit" />
</form>
Now we will use the following code to upload the file:
<?php
$file = JRequest::getVar('file_upload', null, 'files', 'array');
//Import filesystem libraries. It is not necessary
jimport('joomla.filesystem.file');
//Clean up filename to get rid of strange characters like spaces etc
$filename = JFile::makeSafe($file['name']);
//Set up the source and destination of the file
$src = $file['tmp_name'];
$dest = getcwd() . "/uploads/" . $filename;
if ( JFile::upload($src, $dest) ) {
echo "uploaded successfully"; //or we can redirect to a page of our choice
} else {
echo "not uploaded"; // or we can redirect and throw an error message
}
?>
In above example, the file will upload to the uploads folder in the server. Also please check the permission of the folder otherwise the file will not uploaded.
0 Comment(s)