How to create a php upload file with progress bar [duplicate] - php

This question already has answers here:
Upload Progress Bar in PHP
(10 answers)
Closed 9 years ago.
I would like to know how can I add a progress bar in my php upload file.
This is my code:
form.html
http://pastebin.com/embed_iframe.php?i=mukfyVSz
<form id="myForm" action="action.php" method="post">
<input type="file" name="upfile">
<input type="hidden" name="MAX_FILE_SIZE" value="10000">
<input type="submit" value="Upload">
</form>
<div style="margin-top:15px;" id="htmlExampleTarget"></div>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#myForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
// success: function(data) {
// $('.data').html(data);
//}
});
});
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
action.php
http://pastebin.com/vhcH7rTT
<?php
$upload_dir = "./uploads"; // upload folder
$file_name = $_FILES["upfile"]["name"];
// MIME TYPES LIST: http://reference.sitepoint.com/html/mime-types-full
$allowed_types = array("image/gif","image/jpeg","text/html","image/png");
if(!in_array($_FILES["upfile"]["type"],$allowed_types)) {
die("Upload non consentito per questo tipo di file. ");
}
if(trim($_FILES["upfile"]["name"]) == "") {
die("Error1");
}
if(#is_uploaded_file($_FILES["upfile"]["tmp_name"])) {
#move_uploaded_file($_FILES["upfile"]["tmp_name"], "$upload_dir/$file_name")
or die("Error2");
} else {
die("Problems with " . $_FILES["upfile"]["name"]);
}
echo "<div [class='alert alert-success'>Upload with success " . $_FILES["upfile"]"name"] . "</div>";
?>

jquery file upload is better for your need,
just go through the plugin page:
http://blueimp.github.io/jQuery-File-Upload/

Related

uploadprogress_get_info installed correctly and but not working in different code

I know I have no issues with installing uploadprogress extension because when I tried this very simple tutorial: http://www.ultramegatech.com/2010/10/create-an-upload-progress-bar-with-php-and-jquery/, it worked beautifully!
I then tweaked it just a little bit to have a very simple (not jQuery-UI) progress bar, which also worked. Here's the working code:
upload_getprogress.php:
<?php
if (isset($_GET['uid'])) {
$status = uploadprogress_get_info($_GET['uid']);
if ($status) {
echo round($status['bytes_uploaded']/$status['bytes_total']*100);
}
else {
echo 100;
}
}
?>
upload_form.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Upload Something</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
#progress-bar, #upload-frame {
display: none;
}
</style>
<script>
(function ($) {
var pbar;
var started = false;
$(function () {
$('#upload-form').submit(function() {
$('#upload-form').hide();
pbar = $('#progress-bar');
pbar.show();
$('#upload-frame').load(function () {
started = true;
});
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
});
function updateProgress(id) {
var time = new Date().getTime();
$.get('upload_getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
started && $('#inner').css('width', progress+ "%");
});
}
}(jQuery));
</script>
<style>
#progress-bar
{
height:50px;
width:500px;
border:2px solid black;
background-color:white;
margin:20px;
}
#inner
{
height:100%;
background-color:orange;
width:0%;
}
</style>
</head>
<body>
<form id="upload-form"
method="post"
action="upload.php"
enctype="multipart/form-data"
target="upload-frame" >
<input type="hidden"
id="uid"
name="UPLOAD_IDENTIFIER"
value="<?php echo $uid; ?>" >
<input type="file" name="file">
<input type="submit" name="submit" value="Upload!">
</form>
<div id="progress-bar"><div id='inner'></div>
<iframe id="upload-frame" name="upload-frame"></iframe>
</body>
</html>
All fine and dandy, no issues! So I know for a fact there is nothing wrong with the way I've set up the uploadprogress extension.
However, having completed the demo successfully, I needed to integrate it into my javascript and jQuery intensive web-app, which includes file uploads.
Now when I try it, I get “NULL” from the uploadprogress_get_info() function. Why?
In my application page, my image upload form is created dynamically. But at the beginning of my page (and before the user hits a button that dynamically creates an image upload form), I am using this line:
<input type='hidden' name='UPLOAD_IDENTIFIER' id='uid' value='<?php echo md5(uniqid(mt_rand())); ?>' />
Is this the problem? Is there a specific time or place this hidden input should be present?
Before including the above line at the top of my page, I've also included a long .js file that includes a bunch of jQuery plugins, but starts with the following code:
var started = false;
function updateProgress(id) {
console.log("updating progress"); // this msg appears, so i know i'm getting this far
var time = new Date().getTime();
$.get('upload_getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
//started && pbar.progressbar('value', progress);
$('#inner').css('width', progress+ "%");
});
}
// a lot more functions, then:
function imageDialog(imgtype, x, y, editsource) {
// this function dynamically generates a dialog for image uploading
// which shows up when a user hits an "image upload" button
// there's lots of code that creates a new form which is assigned to $imgform
// lots of elements and a couple of iframes are appended to $imgform
// then finally:
$imgform.submit(function() {
pbar = $('#progress-bar');
$('#inner').css('width', "0%");
pbar.show();
started = true;
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
/* other irrelevant stuff */
}
However, while the upload progress bar shows up as expected, it never increases in progress.
So I edited the upload_getprogress.php to look like this:
if (isset($_GET['uid'])) {
$uid = $_GET['uid'];
//$status = uploadprogress_get_info($_GET['uid']);
echo "progress for $uid is: ".uploadprogress_get_info($uid);
}
In Firefox, I can see the response of the ajax call, and what I get as output from upload_getprogress.php is:
progress for 6e728b67bd526bceb077c02231d2ec6f is:
I tried to dump $status into a variable and output to file, and the file said:
the current uid: 02e9a3e0214ffd731265ec5b0b220b4c
the current status: NULL
So basically, the status is consistently returning NULL. Why? This was (and still is) working fine in the demo, what could be going wrong while integrating it into my web app code? There's nothing wrong with the image uploading on its own - my images are getting uploaded fine, but the progress isn't getting tracked!
The form that gets created dynamically looks like this:
<div class="dialog-container">
<form id="imgform" method="post" enctype="multipart/form-data" action="upload_1-img.php" target="upload_target">
Select image:
<br>
<input id="image" type="file" name="image">
<div id="imgwrapper"></div>
<input id="filename" type="hidden" value="" name="filename">
<input id="upath" type="hidden" value="xxxxxxxxxxxxxxxxxxxxxxxxxx" name="upath">
<center>
<input id="imgupload" type="submit" onclick="showUploadedItem()" value="Upload">
<input id="clearcrop" type="button" disabled="disabled/" value="Clear selection">
<input id="imgapproved" type="button" disabled="disabled" value="Done">
<input id="imgcancel" type="button" value="Cancel">
</center>
</form>
</div>
<div id="progress-bar"><div id='inner'></div></div>
<!-- etc etc some other elements -->
</div>
and my own upload_1-img.php starts off with:
$filename = $_FILES["image"]["tmp_name"];
$file_info = new finfo(FILEINFO_MIME);
$bfr = $file_info->buffer(file_get_contents($filename)) or die ("error");
// some more stuff, getting file type and file's $name
if( /* a bunch of conditions */ )
move_uploaded_file( $_FILES["image"]["tmp_name"], $upath . "/" . $name);
Woohoo! I figured it out, thanks to this bug:
https://bugs.php.net/bug.php?id=57505
Basically, just I removed this static line from the page where users get to upload files:
<input type='hidden' name='UPLOAD_IDENTIFIER' id='uid' value='<?php echo md5(uniqid(mt_rand())); ?>' />
and in my javascript function that creates the image dialog dynamically, I just added the hidden input dynamically, right above the line where I generated the file input.
So the relevant part of the dynamically created form then looks like:
<input type='hidden' name='UPLOAD_IDENTIFIER' id='uid' value='1325a38f3355c0b1b4' />
<input id="image" type="file" name="image">
Now since this is getting dynamically created via javascript anyway, I can just replace that value above with a random js function.
Now the progress bar is advancing as it ought to! :D

ajax form data serialization failed

I have a HTML with a form in it like this:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
</head>
<body>
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
Your Photo: <input id="thefile" type="file" name="photo" size="25" />
<input type="button" name="submit" value="Submit" onclick="submitform();"/>
</form>
</body>
<script>
function submitform()
{
data = $('*').serialize();
$.post(
'http://localhost/banksoal/1.0.0/accept-file.php',
data
);
}
</script>
</html>
and the .php script like this:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
print_r($_FILES['photo']);
$message = 'default message';
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = 'd:\\' . '--test-- '.basename($_FILES['photo']['name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
else
{
$valid_file = true;
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], $new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
var_dump($message);
?>
The problem:
in the submitform() function, in the script tag at the line:
data = $('*').serialize();
why I get empty result?
What is wrong with the code?
Thank you
change this
data = $('*').serialize();
to
data = $('theform').serialize();
and change this
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
to
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform" name ="theform">
Give thsi a try as mentioned here: http://api.jquery.com/serialize/
$('form').submit(function() {
console.log($(this).serialize());
return false;
});
You can also use
echo json_encode($data);
http://php.net/manual/en/function.json-encode.php
You cannot upload files using Ajax, if you MUST upload files in an AJAX-like way you can use hidden iframes, set the target attribute equal to the iframe and grab the iframe's content to know whether the request has failed or not
This is what i usually do for this purpose, create a hidden iframe that will be the target to the form, something like this:
<iframe name='formTarget' src='#' style='display:none;' onload='processResult(this);'></iframe>
and in processResult you can fetch the iframe's content by:
$(results).html();
This way when the iframe is loaded it will automatically trigger the function to inform the request is complete

PHP file-upload using jquery post

Let me know if anyone know what is the issue with this code.
Basically i want to upload a file using jQuery
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').submit(function(event) {
event.preventDefault();
$.post('post.php',function(data){
$('#result').html(data);
});
});
});
</script>
</head>
<body>
<form id="form1">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
and my php 'post.php'
<?php
echo $file['tmp_name'];
?>
Uploaded File name is not returned back. Issue is i couldn't access the uploaded file.
Thanks in advance!
Shiv
Basically i want to upload a file using jQuery
You cannot upload files using AJAX. You could use the jquery.form plugin which uses a hidden iframe:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(event) {
$('#form1').ajaxForm(function(data) {
$('#result').html(data);
});
});
</script>
</head>
<body>
<form id="form1" action="post.php" method="post" enctype="multipart/form-data">
<h3>Please input the XML:</h3>
<input id="file" type="file" name="file" /><br/>
<input id="submit" type="submit" value="Upload File"/>
</form>
<div id="result">call back result will appear here</div>
</body>
</html>
Also notice the enctype="multipart/form-data" on the form.
Another possibility is to use the HTML5 File API which allows you to achieve that assuming the client browser supports it.
It's not possible to upload files with jQuery $.post, neverthless, with the file API and XMLHttpRequest, it's perfectly possible to upload a file in AJAX, and you can even know how much data have been uploaded yet…
$('input').change(function()
{
var fileInput = document.querySelector('#file');
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/');
xhr.upload.onprogress = function(e)
{
/*
* values that indicate the progression
* e.loaded
* e.total
*/
};
xhr.onload = function()
{
alert('upload complete');
};
// upload success
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
{
// if your server sends a message on upload sucess,
// get it with xhr.responseText
alert(xhr.responseText);
}
var form = new FormData();
form.append('title', this.files[0].name);
form.append('pict', fileInput.files[0]);
xhr.send(form);
}
No no no, you should use a jQuery form plugin for async uploading files. You can't upload file with jQuery $.post method. The file will be uploaded with hidden iframe
Another way is to use HTML5 uploading with FileAPI/BlobApi
Your upload.php has some error.
you should change your this part.
echo $file['tmp_name'];
to:-
echo $_FILES['file']['tmp_name'];
Try uploading with an iframe because you can't send a file with $.post method.
You could also try jquery uploadify - http://www.uploadify.com/

PHP file upload with iframe - announce start and end of upload

so I have a PHP iframe (ajax) file uploader. I would like to display a loading message when submit is clicked (easy on click event) and then once the file is uploaded, so when the iframe is loaded with the PHP response, vanish (jquery fadeOut) and an alert box pop up saying the file is uploaded. what would be the easiest way to go about this?
You can attach an event handler to load on the iframe and put your fade out logic in there.
Edit 2: Some sample code (changed from ready to load)
<iframe name="process"></iframe>
<form method="post" action="upload.php" target="process" enctype="multipart/form-data" onsubmit="Upload.start()">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
<script>
var Upload = function() {
$(function() {
$('iframe[name=process]').load(function() {
// finished uploading file
$('.loading-div').hide('slow', function() {
alert('Your file has been successfully uploaded.');
});
});
});
return {
start: function() {
$('.loading-div').show();
}
}
}();
</script>

Php - upload file with ajax

my 2form.php :
<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript">
function test()
{
url = '2form.php';
var ajax = new Ajax(url, {
method: 'post',
onComplete: function(response) {
document.getElementById('error_upload_logo').innerHTML = response;
}
});
ajax.request();
}
</script>
<?php
if($_FILES)
{
echo "<div>";
foreach($_FILES['name'] as $v)
{
echo $v."<br/>";
}
echo "</div>";
}
else
{ ?>
<form action='' id='form1' name="form1" method="post" enctype="multipart/form-data">
<input type="file" name="name"/>
<input type="submit" name="submit" onclick='test(); return false;'/>
</form>
<?php
}
?>
<div id="error_upload_logo"></div>
if run code with out javascript , it 2form.php like simple php page, and
we can see information of $_FILES that was printed to scrreen
But if i have run with javascript by test() function ,
i don't get information in $_FILES ?
How to get $_FILES ? when click button run with javascript ?
i want to upload with ajax
You can't do file uploads using AJAX because you won't have access to the local file.
The most common workaround is what the JQuery Form plugin does, creating a temporary iframe and doing a normal form submit into it.
The other alternative is using a Flash-based uploader like SWFUpload or Uploadify.

Categories