I'm trying to upload an image using codeigniter and ajax. I already have the ajax method to insert the field values to the DB, what's the easiest and simplest way to upload my file.
Here's the JQuery custom function:
(function($){
jQuery.fn.ajaxSubmit =
function() {
$(this).submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url: url,
type: "POST",
data: data,
dataType: "html",
success: function(msg) {
$('#main').html(msg);
}
});
return this;
});
};
})(jQuery);
I call it like this:
$(document).ready(function() {
$('#myForm').ajaxSubmit();
});
The function works fine, the data gets inserted in the database and I even have some directories that get created in the model before uploading the image, they are created but the image is not uploaded at all.
I know I need to use a hidden Iframe to do the job, but I dont quite know how to integrate that in my code.
I created custom Ajax File Uploader using CodeIgniter, jQuery and Malsup form plugin. Here is the HTML and Javascript/CSS code. It also support multiple file upload and Progress.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Ajax UP Bar</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('form').submit( function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$(this).ajaxForm({
beforeSend: function() {
status.html();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
});
</script>
</head>
<body>
<form method="post" action="<?php echo base_url('users/upload/'); ?>" enctype="multipart/form-data">
<label for="upload">Select : </label>
<input type="file" name="upload[]" id="upload" multiple="multiple" />
<input type="submit" name="fsubmit" id="fsubmit" value="Upload" />
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
</body>
</html>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
In CodeIgniter Controller :
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Users extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function upload()
{
if (isset($_FILES['upload']['name'])) {
// total files //
$count = count($_FILES['upload']['name']);
// all uploads //
$uploads = $_FILES['upload'];
for ($i = 0; $i < $count; $i++) {
if ($uploads['error'][$i] == 0) {
move_uploaded_file($uploads['tmp_name'][$i], 'storage/' . $uploads['name'][$i]);
echo $uploads['name'][$i] . "\n";
}
}
}
}
}
Hope this helps you. Thanks!!
Related
The percentage of progress bar does not work correctly
The correct progress bar does not work and it's 100% fast
But the file has not uploaded yet
Click the submit button
The progress bar is completed quickly
But still the file is being uploaded
I'm interested in understanding the code forms
<?php
$msg = [
"title file"
,"url file"
,"send file"
];
?>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap-rtl.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<script src="jquery.js" type="text/javascript"></script>
<script src="js/bootstrap.min.js"></script>
<style>
.del {
border-radius: 100%;
display: inline-block;
font-size: 13px;
height: auto;
margin-right: 4px;
padding: 5px;
}
.box {
height: 41px;
padding-top: 2px;
vertical-align: middle;
}
#uploadurl {
border: 1px solid #ccc;
margin-bottom: 7px;
margin-top: 14px;
padding-top: 11px;
}
</style>
<script>
var template = '<div class="form-group box">' +
'<input type="text" class="col-sm-5 form-control" name="title[]" placeholder="<?=$msg[0]?>">' +
'<input type="text" class="col-sm-6 form-control" name="url[]" placeholder="<?=$msg[1]?>">' +
'<i class="fa fa-times" aria-hidden="true"></i>' +
'<div class="progress-bar progress progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div></div>';
$(document).ready(function(){
$('.add').on('click',function (e) {
$("#uploadurl").append(template);
});
$(document).on('click','.del',function (e) {
var del = $(this).closest('.box').index();
$('.box').eq(del).remove();
});
$('#submit').click(function (e) {
e.preventDefault();
$("input[name='url[]']").each(function (index, value){
$('.myprogress').eq(index).css('width', '0');
var url = $(this).val();
var title = $("input[name='title[]']").eq(index).val();
if(title == ""){
title = <?=strtotime(date('Y-m-d h:s:i'))?>;
}else{
title =<?=strtotime(date('Y-m-d h:s:i'))?>+"_"+title;
}
var data = "url="+url+"&title="+title;
$.ajax({
type: 'POST',
url: "upload.php",
data: data,
datatype:"json",
// contentType: "application/x-www-form-urlencoded",
processData: false,
// this part is progress bar
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function (data) {
$('#fileupload').append("<a style='display: block' href='"+data+"'>"+data+"</a>");
}
});
});
});
});
</script>
<div class="container">
<form id="upload-form" method="post">
<div id="uploadurl" class="col-md-12">
<div class="form-group box">
<input type="text" class="col-sm-5 form-control" name="title[]" placeholder="<?=$msg[0]?>">
<input type="text" class="col-sm-6 form-control" name="url[]" placeholder="<?=$msg[1]?>">
<div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
</div>
</div>
<div style="display: block">
+
<input type="submit" class="btn btn-primary" id="submit" value="<?=$msg[2]?>" name="submit">
</div>
</form>
<div id="fileupload">
</div>
</div>
upload.php
$title = $_POST['title'];
$url = $_POST['url'];
$now = date('Y-m-d h:s:i');
$partition = date('Ym', strtotime($now));
$folder = "file/attach/".$partition."/";
if (!file_exists($folder)) {
$old = umask(0);
mkdir($folder, 0777);
umask($old);
}
$p = pathinfo($url);
$newfile = $folder.$title.".".$p['extension'];
if ( copy($url, $newfile) ) {
echo $newfile;
}else{
echo "false";
}
Click on the link below to view the demo
In the firebug you see, the file is still being uploaded
But the percentage of progress has been 100%.
demo
When I needed a progress bar to add to my file downloads(in my project); I used this code. I have tested this code also. Try the code below; I am quite sure it will serve your purpose:
<!doctype html>
<head>
<title>File Upload Progress Demo</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius:
10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding:
1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px;
}
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js">
</script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
My php upload file:
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error in the upload, please try again!";
}
?>
Hope it helps you and serve as a documentation for you...Happy coding
Here is my main html file;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create Template</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel = "stylesheet"
type = "text/css"
href = "jquery-ui-1.11.4.custom/jquery-ui.css " />
<style type = "text/css">
.dragMe {
width: auto;
height: auto;
/* border: 1px solid blue; */
text-align: center;
background-color: white;
position: absolute;
display:inline-block;
z-index: 100;
}
.dragMeImage {
width: 180px;
height: 55px;
border: 1px solid blue;
text-align: center;
background-color: white;
position: absolute;
z-index: 100;
}
#target {
width: 400px;
height: 600px;
border: 1px solid red;
text-align: center;
position: absolute;
left: 400px;
top: 100px;
z-index: 0;
}
</style>
<script type = "text/javascript"
src = "jquery-1.12.4.min.js">
</script>
<script type = "text/javascript"
src = "jquery-ui-1.11.4.custom/jquery-ui.min.js">
</script>
<script type = "text/javascript" src="ajaxshow.js">
</script>
<script type = "text/javascript">
$(init);
function init(){
//make all drag me elements draggable
$(".dragMe").draggable();
$(".dragMeImage").resizable({
//aspectRatio: 3.2
});
//set target as droppable
$("#target").droppable();
//bind events to target
$("#target").bind("drop", changeTarget);
$("#target").bind("dropout", resetTarget);
} // end init
function changeTarget(event, ui){
$("#target").addClass("ui-state-highlight")
.html("Dropped ")
.append(ui.draggable.text());
} // end changeTarget
function resetTarget(event, ui){
$("#target").removeClass("ui-state-highlight")
.html("Drop on me");
} // end reset
</script>
</head>
<body id="page2">
<form id=form enctype="multipart/form-data" method="post" action="show_images.php">
<input type="submit" value="Continue"/>
</form>
<div id="preview"></div>
<div id="err"></div>
<!-- <h2>Create an Invitation Template to be Sent to the List Owners</h2>
<div class = "dragMe">
<img class = "dragMeImage" src="garbo.png" alt="Garbo Logo" style="width:180px;height:120px;">
</div>
<div class = "dragMe">
<img class = "dragMeImage" src="CA.png" alt="Garbo Logo" style="width:180px;height:55px;">
</div>
<div class = "dragMe">
<img class = "dragMeImage" src="CA1.png" alt="Garbo Logo" style="width:180px;height:55px;">
</div>
<div id = "target">
Drop on this template
</div> -->
</body>
</html>
Here is ajaxshow.js;
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "http://localhost/phpexamples/show_images.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid file')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
and here is the PHP file;
<?php
$folder = "uploads/";
if(is_dir($folder)){
if($handle = opendir($folder)){
while(($file=readdir($handle)) != false){
if($file==='.' || $file==='..') continue;
list($width, $height) = getimagesize("uploads/$file");
$h=150/$width*$height;
$aspect = $height / $width;
if ($aspect >= 1) $mode = "vertical";
else $mode = "horizontal";
echo '<div class = "dragMe">';
echo '<img class = "dragMeImage" src="uploads/'.$file.'" width="150" height="$h" alt="">';
echo '</div>';
}
closedir($handle);
}
}
?>
When I load the images in static HTML (commented out) it works fine. When I run the code above it loads the first image in the directory but it's not draggable or resizable. When I take the class ID's out of the echo part of the PHP file. It loads the images OK but of course they are not draggable or resizable. Can anyone help. Many thanks. Neil.
Since you are adding content dynamically after the image has been uploaded, you will need to call .draggable() on the new elements.
I would advise doing this once your AJAX completes:
$.ajax({
url: "http://localhost/phpexamples/show_images.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function() {
$("#err").fadeOut();
},
success: function(data) {
if(data=='invalid file') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
$("#preview").find(".dragMe").draggable();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
Well I am not able to send form multiple times. The initial part of the code of AjaxForm is working fine whereas the FormData is not working. Instead it send the data in the url without the page like
index.php?photos[]=&username=dfdfdf. The Earlier part is used for image storage and second part is used for user data storage. My requirement is to use single form to send data to different table in database. When the user click submit the data is stored in the data table and the uploaded image also gets updated with that user ID.
Hope You will solve the problem!
<?php
session_start();
include("db.php");
$str = "select * from fileupload order by id DESC";
$res = mysql_query($str);
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.wallform.js"></script>
<script>
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
$("#imageform").ajaxForm({
url : 'ajaxImageUpload.php',
target: '#preview',
beforeSubmit:function(){
console.log('ttest');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('test');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('xtest');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
$(".del-pic").live("click", function(){
var sel1 = $(this).closest('.imgList');
var del_id = $(this).attr('id');
$.post("deleteimage.php", {
del_id : del_id
},
function(data, txtStatus) {
sel1.fadeOut('slow', function()
{
sel1.remove();
});
});
});
$("#uploadTrigger").click(function(){
$("#photoimg").click();
});
$("#upbutton").live("click", function(){
$("#imageform").bind('submit',function(e){
if(window.FormData !== undefined) // for HTML5 browsers
{
var formdata = new FormData(this);
$.post({
url : "insertuser.php",
type : "POST",
data : formdata,
mimeType : "multipart/form-data",
contentType : false,
cache : false,
processData: false,
success: function(data, txtstatus, jqXHR)
{
alert('success');
},
error: function(data, txtstatus, errorthrown)
{
alert('error');
}
});
}
else
{
alert('HTML5 not supporting in your browser');
}
});
});
});
</script>
<style>
#preview
{
color:#cc0000;
font-size:12px;
background: #066;
}
.imgList
{
max-height:100px;
margin-left:10px;
border:1px solid #dedede;
padding:4px;
float:left;
}
.hidden
{
display: none;
}
#uploadTrigger
{
cursor: pointer;
border: 1px solid #333;
padding: 10px;
margin: 5px 5px 5px 5px;
background: #777;
color: #fff;
width:75px;
border-radius: 20px;
font-family:arial;
}
.del-pic
{
background-image:url(../../Krishna/images2/closebox.png);
width:30px;
height:30px;
display:block;
position: absolute;
margin:-10px 0 0 85px;
}
</style>
</head>
<body>
<div>
<div id='preview' style="">
<?
while($row = mysql_fetch_array($res))
{
echo "<div class='imgList'><div class='del-pic' id='".$row['id']."'></div><img src='".$row['filename']."' width='100px' height='100px' ></div>";
}
?>
</div>
<form id="imageform" name="imageform" enctype="multipart/form-data" style="clear:both">
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<div id="uploadTrigger">Add Photo</div>
<input type="file" name="photos[]" id="photoimg" class="hidden" multiple="true" />
<input name="username" type="text" id="username" />
<input type="submit" value="Upload" id="upbutton" />
</div>
</form>
</div>
</body>
</html>
i have a multiple file upload code below. What i want to do is I want to replace the progress bar in this code with the custom label progress bar from jqueryui.com .I really dont have any idea how do i do it. can anyone help?
Here's the code:
<!doctype html>
<head>
<title>File Upload Progress Demo #2</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #2</h1>
<code><input type="file" name="myfile[]" multiple></code>
<form action="file-echo2.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile[]" multiple><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
//console.log(percentVal, position, total);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
<script type="text/javascript">
_uacct = "UA-850242-2";
urchinTracker();
</script>
Here's PHP script to upload files:
<?php
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
echo "<br>uploaded: " . $n[$i] . " (" . $s[$i] . " bytes)";
}
}
else
echo "<br>uploaded: $n ($s bytes)";
}
?>
Here's the code for Custom Label Progress bar :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Progressbar - Custom Label</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.progress-label {
float: left;
margin-left: 50%;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
}
</style>
<script>
$(function() {
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" );
},
complete: function() {
progressLabel.text( "Complete!" );
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 );
if ( val < 99 ) {
setTimeout( progress, 100 );
}
}
setTimeout( progress, 3000 );
});
</script>
</head>
<body>
<div id="progressbar"><div class="progress-label">Loading...</div></div>
</body>
</html>
you can try the "if".
if(percentVal == 50);){
percent.html("you´re text here.");
}
you can create another HTML tag and do the same of the percent var.
var uploadText = document.getElementById(".newTag") or $('.newTag');
if(percentVal == 50);){
uploadText.html("you´re text here.");
}
I am trying to make an ajax based progress bar. But, I don't know how to calculate how much data has been uploaded which I'd like to show as a percentage of data uploaded.
Thank you
You can use APC or the PEAR Package Upload progress.
http://pecl.php.net/package/uploadprogress
Haven't done this in a while, I remember there being an issue with Webkit and having to use an iframe. Might want to look into that.
Try this:-
Demo url:--
http://jquery.malsup.com/form/progress.html
You can download jQuery file from this url and add in html tag
http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js
http://malsup.github.com/jquery.form.js
Try this:
This is my html markup:
<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
My php code:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>