php file upload with a progressbar or number of percent - php

I want to use a file upload progress. Can anybody give possible simple code
for showing upload progess bar. On the next code.
There is file receiving file upload.php
<?php
if ($_FILES) {
foreach ($_FILES as $k => $v) {
if ($v["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $v["name"] . "<br>";
echo "Type: " . $v["type"] . "<br>";
echo "Size: " . ($v["size"] / 1024) . " kB<br>";
echo "Stored in: " . $v["tmp_name"]. "<br><br>";
}
}
return;
}
?>
And there is a html with file upload form.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="f1">Filename:</label>
<input type="file" name="f1" id="f1"><br>
<label for="f2">Filename:</label>
<input type="file" name="f2" id="f2"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
Thank you

The easiest way to do it is to use jQuery uploadify plugin, which includes swfobject and shows file upload progress bar. And it's a beautiful way of uploading multiple files.
jQuery uploadify plugin:
http://www.uploadify.com/
If you want to do it your own way you need server-side compatibility, some nginx or apache2 module that can handle upload progress. And your client-side should make a requests to server during all upload process to get all information about it.

You can use jQuery form plugin to achieve this.
Just add jQuery Form plugin to your page head section. And you can use the following code.
$(function() {
$(document).ready(function(){
var percent = $('#percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
});
I got it from this File Upload Progress Bar Tutorial. And it is working absolutely fine.

Related

Empty $_FILES while AJAX Uploading

I Have got the Following Problem:
I'm trying to Upload a File via a Form over Ajax
Here is the HTML File:
<html>
<header>
<link rel="stylesheet" href="useme.css"/>
<script src="jq.js"></script>
<script src="actions.js"></script>
</header>
<body>
<form enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="file" id="file" name="file"/>
<input type="button" value="Click" id="submitBtn"/>
</form>
<span class="status">no status</span>
</body>
The JavaScript File:
/**
* Created by Kenny on 12.04.2015.
*/
$(document).ready(function(){
$("#submitBtn").click(function(){
var filename = $("#file").serialize();
$.ajax({
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
url: "upload.php",
enctype: 'multipart/form-data',
data : {
file: filename
},
type : "POST",
success: function(data){
if(data != "fail")
$(".status").html("Upload is availible at: " + data);
else
$(".status").html("Upload failed.");
}
});
});
});
And last but not lately the PHP File that does the Magic (Not really atm)
<?php
/**
* Created by PhpStorm.
* User: Kenny
* Date: 12.04.2015
* Time: 23:55
*/
$uploaddir = '/many/upload/' . uniqid() . '/';
if(!file_exists($uploaddir)){
mkdir($uploaddir, 0777, true);
}
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://use.hints.me/" . $uploaddir;
file_put_contents($uploaddir . "/index.php", "<?php Header('Location: " . basename($_FILES['userfile']['name']) . "'); ?>");
} else {
echo "fail";
}
?>
My Problem here is that I only get empty $_FILES in the PHP-File, the PHP File somehow works fine when i use a Standard POST form, but with Ajax it doesnt work at all.
Excuse my messy Code, it's just a Proof of Concept to a friend of mine and not at all used for Providing a serious File Upload site. I just want to get this working.
Things i checked here before:
check the php.ini File if the File Upload is enabled
added enctype="multipart/form-data" to the Form
added the MAX_FILE_SIZE tag to the Form
checked StackOverFlow all over

php and jquery progress bar

I have one form and in that form i have input type file to upload zip files i upload zip file using that form and than it goes to zip extract php file but i want to show loader till the file extract.How can i do using php or jquery?
<form enctype="multipart/form-data" method="post" action="zip_upload.php">
<label>Upload Zip File: </label> <input type="file" name="zip_file">
<input type="submit" name="submit" value="Upload" class="upload" id="submitzip"> <br><br>
</form>
Showing a percentage based progress bar is tricky work. You're much better off displaying a loading status or a spinning icon if your knowledge on this subject is limited.
Not the prettiest of methods but has worked wonders for me and many others in the past.
CSS:
#uploadFrame {
height:1px;
width:1px;
visibility:hidden;
}
HTML:
// hide this on your page somewhere. It's only 1x1 pixels, so should be simple.
<iframe src="zip_upload.php" name="uploadFrame" id="uploadFrame"></iframe>
// your upload form
<form enctype="multipart/form-data" method="post" action="zip_upload.php" target="uploadFrame">
// form content
</form>
jQuery:
$(form).submit(function() {
$('#loading-spinner').show();
});
$("#uploadFrame").load(function() {
$('#loading-spinner').hide();
});
When the form is submitted, a loading icon is displayed, and when the upload and extraction process has finished (iFrame loaded), the loading icon disappears. This all happens without reloading the page.
The bonus of using this is, if modified slightly (convert jQuery to Javascript) you don't need any external libraries or plugins to use it. Also, it is very simple and understandable.
ANOTHER OPTION --------------------------------------------
A bit more advanced and inclusion of jQuery library & a plugin is required, but has the percentage feature.
Check out http://malsup.com/jquery/form/#file-upload for documentation and full spec and here for demo: http://malsup.com/jquery/form/progress.html.
Here is the code:
<form action="zip-upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="zip_file">
<input type="submit" value="Upload">
</form>
<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);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
And on your PHP page:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['zip_file']['name']);
if(move_uploaded_file($_FILES['zip_file']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['zip_file']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
You can use jQuery UI. Here you can check it http://jqueryui.com/progressbar/#default

File Upload Progress for Dynamic Dropdown File Upload

I have made a dynamic dropdown file upload system where user can choose the engineering stream, then the semester and then subject, and the file gets uploaded in the desired directory. This works fine normally. I came across the Javascript/AJAX File Upload Progress tutorial from PHPAcademy, things worked fine until I got stuck into this.
Without adding the javascript file (for upload progress), the files get uploaded in the correct directory, show no errors in the firebug, and also gives the link to the file after it gets uploaded.
But after I add the JS file, the link doesn't come after upload, it gets uploaded in the root directory always, it shows the progress though, and the console shows two errors.
Here is my PHP code:
<?php
if(isset($_POST['upload'])) {
$path1=$_POST['one']."/";
$path2=$_POST['two']."/";
$path3=$_POST['three']."/";
$upload_path=$path1.$path2.$path3;
}
else {
echo "Follow the instructions before uploading a file";
}
if(!empty($_FILES['file'])) {
foreach($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key]==0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], $upload_path."$name")) {
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])) {
die(json_decode($uploaded));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> SRMUARD - Upload </title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
function val()
{
if(document.uploads.three.selectedIndex == 0)
{
alert("Please choose all the appropriate options");
}
}
</script>
<script>
$(function() {
$("#text-one").change(function() {
$("#text-two").load("textdata/" + $(this).val() + ".txt");
});
$("#text-two").change(function() {
$("#text-three").load("textdata/" + $(this).val() + ".txt");
});
});
</script>
</head>
<body>
<div value="<?php $upload_path ?>" id="uploadpath"></div>
<div id="uploaded">
<?php
if(!empty($uploaded)) {
foreach($uploaded as $name) {
echo 'File Link: '.'<a href="' . $upload_path . $name . '" >', $name, '</a><br/>';
}
}
?>
</div>
<div id="upload_progress" style="display: none"></div>
<div>
<form action="" method="POST" enctype="multipart/form-data" name="upload" id="upload">
<label for="file">Choose a file: </label><br/>
<input type="file" name="file[]" id="file" multiple="multiple"><br/><br/>
<select id="text-one" name="one">
<option selected value="base">Select Department</option>
<option value="CSE" name="cse">Computer Science Engineering</option>
<option value="ECE" name="ece">Electronics & Communication Engineering</option>
<option value="MECH" name="mech">Mechanical Engineering</option>
</select><br/><br/>
<select id="text-two" name="two"> //Displays options dynamically using text files
<option>Select Semester</option>
</select><br/><br/>
<select id="text-three" name="three"> //Displays options dynamically using text files
<option>Select Subject</option>
</select><br/><br>
<input type="submit" name="upload" id="submit" value="Upload" onClick="val()" />
</form>
<div>
</body>
</html>
And here is my javascript code:
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for(var i = 0; i < fileInput.files.length; ++i) {
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event) {
if(event.lengthComputable) {
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
}
});
request.upload.addEventListener('load', function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Upload failed due to some reason!');
});
request.addEventListener('readystatechange', function(event) {
if(this.readyState == 4) {
if(this.status == 200) {
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
var phpval = document.getElementById('uploadpath').value;
for(var i=0; i < uploaded.length; ++i) {
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', phpval + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
} else {
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control','no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load',function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
And the errors shown in the console are:
TypeError: document.uploads is undefined
[Break On This Error]
if(document.uploads.three.selectedIndex == 0)
and
SyntaxError: missing ; before statement upload.js file line 47 which is var uploaded = eval(this.response);
And another place where I feel I am making a mistake is:
a.setAttribute('href', phpval + uploaded[i]);
The phpval must correspond to the dynamic upload link. I couldn't use the $upload_path in the JS, so made a div out of it, and then used to get the value like this:
var phpval = document.getElementById('uploadpath').value;
For the demo, you can refer this link, things will be more precise, please turn on your firebug console and check the errors and help me. I am not able to solve this.
Dynamic Dropdown File Upload with Progress Indication
Thank You
Also consider positioning of your script properly. Sometimes what happens is the place where you place your script might cause conflicts. I can see that you have the scripts for Dynamic Dropdown Functionality already. Try placing it after your form and check if it works.
Hope this helps.
There are many JQuery options you could try. Here is one from Blueimp. Hope this helps.

Ajax file upload not working in I.E

I am uploading images using ajax and php. My code is working fine in firefox. But in I.E, it doesn't work!
Here is my HTML code,
<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
body { padding: 30px }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<form action="fileup.php" method="post" enctype="multipart/form-data">
<input id="inp" type="file" name="uploadedfile" style="display:none"><br>
<input id="btn" type="submit" value="Upload File to Server" style="display:none">
</form>
<div id="fileSelect" class="drop-area">Select some files</div>
<script>
(function() {
$('form').ajaxForm({
complete: function(xhr) {
alert(xhr.responseText);
}
});
})();
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("inp");
fileElem.addEventListener("change",function(e){
document.getElementById('btn').click();
},false)
fileSelect.addEventListener("click", function (e) {
fileElem.click();
e.preventDefault();
}, false);
</script>
</body>
</html>
Here is php code,
<?php
$target_path = "images/";
$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!";
}
?>
In firefox the file uploads perfectly and alert comes up, But in I.E nothing happens!
From the examples page of the form plugin
Browsers that support the XMLHttpRequest Level 2 will be able to
upload files seamlessly.
IE doesn't support XMLHttpRequest Level 2.
EDIT:
Okay, it doesn't seem to be an Ajax issue, because the plugin uses a iframe fallback. You may need to refactor your javascript code
$(function(){
$('form').ajaxForm({
complete: function(xhr) {
alert(xhr.responseText);
}
});
$('#inp').change(function(e) {
$('#btn').click();
});
});
But as a side note, file drop is also not available in IE. So it only works if you select a file manually in IE. And a hidden file select will not allow the user to select a file. Raising the click event from javascript on a file input is also not possible, you have to go with a transparent file input.

JQuery Validation for input type file failing on server side

So I'm trying out a very simple form with one field to upload an image. The input type is a file. There's a submit button also. The form has no action="" and the validation on the client side happens using the Jquery Validation plugin. Validation on the client side happens perfectly (It returns file type error), but as soon as I click upload, the upload is failing on the server side (PHP file). I don't think the file is being read on the server side since the if condition fails. My code is this:
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script language="javascript">
$(document).ready(function(){
$("#upload").validate({
debug: false,
rules: {
file: {required: true, accept: "gif|png|jpg|jpeg"}
},
messages: {
file: "*Please select a file",
},
submitHandler: function(form) {
// do other stuff for a valid form
var phpurl = 'upload_file.php';
$.post(phpurl, $("#upload").serialize(), function(data) {
alert(data);
});
}
});
});
</script>
The PHP Code:
<?php
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
{
if ($_FILES["file"]["error"] > 0)
{
print "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
print "Upload: " . $_FILES["file"]["name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
print $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
print "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
print "Invalid file";
}
?>
The ouput I receive as an alert - is always invalid file.
If I try the form without the Jquery validation and directly using the action="upload_file.php method, it perfectly works. What is the problem?
HTML:
<form id="upload" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
You need to use useful jQuery validation plugin which does support the files you want to allow for upload other than other nice options.
You can use the accept property of the validation plugin to allow file types you want, here is an example:
$("#form_id").validate({
rules: {
field: {
required: true,
filesize: 1048576,
accept: "gif|jpeg"
}
}
});
The problem is that files can't be submitted through ajax post as PHP won't upload them to the server.
In theory you should create an iframe and make the form submit there. In practice just use this jquery plugin... http://jquery.malsup.com/form/ :) It will ease up the process
Hope it helps.
Is it possible to use Ajax to do file upload?

Categories