you can upload you're file with ajax if you create a controller with php:
<?php
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // Autorized extensions
$max_size = 200 * 1024; // Max file size
$path = 'uploads/'; // Folder where to upload
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if( ! empty($_FILES['image']) )
{
// Get the extension of the file
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// Test the file format if it's allowed
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'] < $max_size)
{
$path = $path . uniqid(). '.' .$ext;
// Put the file in the folder of uploads
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
echo $path; // returning the path
else
echo 'uploads/err.gif'; // returning the error message or path or whatever
}
else
echo 'uploads/err.gif';
}
else
echo 'uploads/err.gif';
}
else
echo 'uploads/err.gif';
?>
In you're view, you have to include jQuery.form library and. you create a form, and inside the form you put an image and a button, the form should have the link of you're php file as action, and call this function:
$('#form').ajaxUpload($('#button'),$('#image_preview'));
The definition of ajaxUpload
function is this:
jQuery.fn.ajaxUpload = function(Button,Preview)
{
var Frm = $(this); // form
var Btn = Button; // upload button
var Prev = Preview; // preview area
Btn.click(function()
{
// implement with ajaxForm Plugin
Frm.ajaxForm(
{
beforeSend: function()
{
Btn.attr('disabled', 'disabled');
Prev.fadeOut();
},
success: function(Result)
{
Frm.resetForm();
Btn.removeAttr('disabled');
Prev.attr("src",Result).fadeIn();
},
error: function(Result)
{
Btn.removeAttr('disabled');
Prev.attr("src",Result).fadeIn();
}
});
});
};