Adding unobtrusive progress bar to old-school file uploads - php

You all know the new generation of fancy, mostly Flash-based file uploaders like SWFUpload that can show a progress bar while uploading - a great improvement especially for shaky and low-bandwidth connections.
However, these uploaders all bring their own logic of how to handle uploads on the client side. I am looking for an unobtrusive way to "fancify" existing, classical file uploads, i.e. introducing a progress bar to normal file upload forms.
Due to the architecture of uploading files, this is most likely not possible without some tweaking on the client side.
I am looking for a solution that keeps the tweaking to an absolute minimum, e.g. a component that adds itself to the onsubmit event of a normal form, performs the file upload, displays a nice progress bar, puts the resulting temporary (server side) file path into the form, and submits it.
On the server side, I just have to modify my script to use the file path provided by the flash uploader, instead of $_FILES and consorts, and think about security for a moment.
This is not exactly what all the Flash-based uploaders do: They can use data from a form, but they do not provide possibilities to submit the form as is, what is what I'm looking for. I am looking for a (probably) Flash based upload function taken a step further.

If you use PHP 5.2 and up this file upload progress tutorial by IBM can help you.
This multiple file upload tutorial uses jQuery + AJAX Upload... It uses $_FILES on the server side and will transform a special <div> on the client side to make a <form>. I guess you could tweak it to fit your needs.
If tweaking the last one is too tricky, Uber-Uploader on SourceForge is another option.
There are dozens of open source project covering this topic. Unfortunately this is not something trivial to implement seamlessly (at least in the way you want - otherwise we would have saw this in the good old Netscape days already).
On the bright side, HTML5 will ease this as you can see in this demo and this one.
I hope this helps and good luck with you integration.

We implemented this very simple by installing the PECL extension pecl-uploadprogress and added a simple AJAX callback to the forms:
Generate an upload key:
$upload_id = genUploadKey();
function genUploadKey ($length = 11) {
$charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for ($i=0; $i < $length; $i++)
$key .= $charset[(mt_rand(0,(strlen($charset)-1)))];
return $key;
}
Create an AJAX callback handler (eg. uploadprogress.php):
extract($_REQUEST);
// servlet that handles uploadprogress requests:
if ($upload_id) {
$data = uploadprogress_get_info($upload_id);
if (!$data)
$data['error'] = 'upload id not found';
else {
$avg_kb = $data['speed_average'] / 1024;
if ($avg_kb<100)
$avg_kb = round($avg_kb,1);
else if ($avg_kb<10)
$avg_kb = round($avg_kb,2);
else $avg_kb = round($avg_kb);
// two custom server calculations added to return data object:
$data['kb_average'] = $avg_kb;
$data['kb_uploaded'] = round($data['bytes_uploaded'] /1024);
}
echo json_encode($data);
exit;
}
// display on completion of upload:
if ($UPLOAD_IDENTIFIER) {
...
Download jQuery and the jQuery.uploadprogress libraries (which also includes the above snippet) and integrate with your form:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.uploadprogress.0.3.js"></script>
<script type="text/javascript">
jQuery(function () {
// apply uploadProgress plugin to form element
// with debug mode and array of data fields to publish to readout:
jQuery('#upload_form').uploadProgress({
progressURL:'uploadprogress.php',
displayFields : ['kb_uploaded','kb_average','est_sec'],
start: function() {
$('.upload-progress').show();
},
success: function() {
$('.upload-progress').hide();
jQuery(this).get(0).reset();
}
});
});
</script>
Add this to your upload form:
<input name="UPLOAD_IDENTIFIER" type="hidden" value="$upload_id" />
That should do the trick. This is extracted from our code base and may not work out-of-the-box. But it should tell you the idea.

jquploader uses the info inside the form, such as the action attribute value as upload script. But i haven't updated it in a while and it lacks all the belts and whistles scripts like uploadify have (which is an excellent script btw). See if it could be a base for you to tweak.

Does the technique used in Uploadify (a jQuery plugin) meet your needs? Demo

How funny, I just saw Simon Willison blog about Plupload, which is a JavaScript library that I think does file upload progress bars (amongst other things).
It uses Flash, Silverlight, or whatever’s available, but I think abstracts all that away from you, so you’re still uploading with a regular HTML form.

You'll have to check the size of the part of the file wich is allready on the Server, then get it on the Client per Ajax where you can paint the progress bar. (Remember to check the size of the hole Data before, to calculate the percantage ;-) )

Related

How to read a log file live that is constantly updating in server to web textbox

the log file will be in notepad format the values will be like this 11.23445646,56.3456578954
10.23445646,26.3456578954
16.23445646,-46.3456578954
I'm planning to get the data from server to website textbox, of first value which I marked as italic the values will change after few seconds the updated value will come first. I tried some PHP example but not getting it in the below text box the values I need to get.. for example: x=11.23445646, y=56.3456578954, pls guide me
Longtitude <input id="x" type="number" value = "" onkeyup="updateMarker('x')">
Latitude <input id="y" type="number"value = "" onkeyup="updateMarker('y')">
Updated Answer
You can do this now using Web Socketing. Here is a guide and hello-wrold example of a php websocket server:
http://socketo.me/docs/hello-world
And to see how to implement client side javascript of websocket, you can see the bottom of the link put above, which shows you this snippet:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
Old
PHP does not support live connections generally in the way you expect, you have to simulate it via repeated AJAX request. How? For instance on each second, or each two seconds.
You first have to write an ajax in your HTML with jQuery library:
Sending a request each second:
var url = "url_to_you_file";
var textarea_id = "#textarea";
setInterval(function(){
$.ajax({
url : "site.com/get-file-logs.php",
type : "POST",
success : function(data){
$(".textarea").html(data);
}
});
}, 1000);
Then in PHP file you would write this:
$file_path = "path_to_your_file";
$file_content = file_get_contents($file_path);
echo $file_content;
The above example gets the file content and sends it back to your browser. You may want to process it in a certain way; that then changes your approach a little bit. Because you must always stick to JSON format when you try to get data back from server to be manipulated by Javascript.
PHP doesn't really do "live" page updates since normally when a web browser (or other user agent) loads a web page once it's done downloading the page then PHP is already finished and can't touch what's already on the client.
Best way to do this would probably be to use a JavaScript AJAX call to periodically load the updated values from a PHP script and then update the values on the page.
Or if it's a really small page (in byte size) you could just make it automatically reload the whole page (with updated values) if that is not a problem for you.
In any case every time the PHP script is called it would just open the file in read mode and only read the latest values from the beginning of the file and return those. See fread(). Or maybe file_get_contents() or file() would be easier and just read the first line.
AJAX is a bit larger topic and I don't currently have the time to explain the whole process of updating the page using JavaScript. Google is your friend.

Post web image to a server

I've read many posts that due to security risks you cannot upload to your server with an image from your folder as javascript isnt allowed such access. However, I have a situation where i have an svg image on a web site that I convert to a png whilst on the website. But, I wish to send the converted image to my server.
Will I encounter the same problems as if I were uploading from my documents?
I tried to make an example of jsfiddle but it seems it doesnt accept document.write very well, so here's sort of a work-around:
DEMO: jsfiddle
Ideally we would have a button defined as so:
<button id="image" onClick="image()">Convert & Send</button>
Then have the code that does the conversion within a function along with the ajax
function image() {
//conversion code & ajax
}
So in conclusion I would just like to know if this is possible if not, i would be grateful if you could show an alternative way, whether it may include a combination of php.
thanks in advance
It seems as though the fiddle isnt loading heres the snippet: of the conversion
function image () {
var svg = document.getElementById("svg-container").innerHTML.trim();
var canvas = document.getElementById('svg-canvas');
canvg(canvas, svg, { renderCallback: function () {
var img = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
}
});
I'm not sure about what your question is, but indeed, you can use a combination of Ajax + PHP to upload your image.
The client would POST an encoded image (e.g. encoded in Base64) using ajax (using jQuery.post, for example), while the PHP would receive the image and store it (after decoding it) in your server.
For an example of the process, check this question, where a specific case of a canvas is discussed. I think your SVG conversion could work in a similar way.
PS: For some reason, I couldn't load your Fiddle.
EDIT:
So both Ajax & PHP are written on the front end to send the image to
my server/database (ruby on rails). Is that correct?
No. Only Javascript (with Ajax) is used in the client. PHP would be the server part of the process, so in your case it would not be used as you are already using Ruby on Rails. In other words:
The client (browser) uses Javascript (maybe JQuery) to POST the image data (in your snippet, img) to the server (more info here).
The server (a PHP, ASPX or Ruby script [among others]) gets the POSTed data and saves the picture on disk (some info here).
If you can use PHP (in the server) for the specific process of saving the image, you can use the question I linked before as a guide.
Yes Of Course Their are ways:
I know 2:
1-(This One I know it works on chrome and Firefox but don't know IE):
First Get The Base 64 Data Of An Image In Canvas:
<canvas id="Canv" ....(Other Attributes)>
Your Browser does not support the canvas element :(
</canvas>
<button type="button" OnClick="Image()">Transform and Save</button>
<script type="text/javascript>
var can =document.getElementById('Can');
var ctx = can.getContext("2d");
//do something with ctx
function image(){
//You Should check the real format using img.src
var data = can.toDataURL("image/png");
var array = data.split(".");
var Base64Data = array[1];
//Now step 2 :Sent it to PHP
//Check for Browser compatibly
var ajx = new XmlHttpRequest()
ajx.onreadystatechange=function()
{
if (ajx.readyState==4 && ajx.status==200)
{
if(ajx.ResponseText == "Err"){//if the paged returned error
alert("An error Has Occurred");
return;
}//if not
alert("Saved Succesufuly");
}
}
ajx.open("GET","Save.php?q=" + Base64Data , true);
}
</script>
Step3: Interprete it With PHP
<?PHP
if(isset($_GET['q] And !Empty($_GET['q'])){
try {
$Data = $_GET['q'];
$hndl = fopen("Saved/Pic1.jpg" , "w");
fwrite($hndl , $Data);
fclose($hndl);
}catch(Exception $err){
echo "Err";
}
}else {
echo "Err";
}
?>
Yeap And That it.:D
You Could also loop throught each file in that directory and create a load button that get the Base64 Value And the first stuffs and out it into canvas using pucontent method of canvas element object

Phonegap blackberry photo upload server php script

There are many people asking questions related to this issue, but none are complete enough for me to solve my issue.
I have created a fully working HTML5 smartphone app, based on phonegap, for.. shudder... Blackberry that is sending data nicely to a remote MYSQL server using a server side php script.
However I want to give the option to also upload a photo as this is injury prevention, and hazards need photographing. This is a NON commercial product, it is a working example of modern smartphone technologies and to demonstrate how one app can be ported easily to various smartphones.. Blackberry is the common phone and has to be the prime example.
I cannot for love nor money find any working examples of an app and a php server side script together.
The example I have extracted from the CORDOVA example file takes a picture, and I can see the generated thumbnail in my app, and that bit is all sweet (based on all code you see below), but I dont know what I need to program for my upload.php to do something. Everything I try just fails with error code 3 and 1..
Here is the important code for the webapp.
HTML
<h3>navigator.camera</h3>
<input type="button" value="Get Photo (Data)" onclick="capturePhoto();return false;" />
<input type="button" value="Get Photo (URI)" onclick="capturePhotoURI();return false;" />
<img style="display:none;width:120px;height:120px;" id="cameraImage" src="" />
<p id="uploadProgress"></p>
<input style="display:none;" id="uploadButton" type="button" value="Upload" onclick="uploadImage();return false;" />
JAVASCRIPT
function capturePhotoURI() {
navigator.camera.getPicture(onCapturePhotoURISuccess, fail,
{ destinationType: Camera.DestinationType.FILE_URI, quality: 50 });
}
function onCapturePhotoURISuccess(imageURI) {
if (imageURI != null) {
var smallImage = document.getElementById('cameraImage');
var uploadButton = document.getElementById('uploadButton');
// Unhide image elements
smallImage.style.display = 'block';
uploadButton.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
smallImage.src = imageURI;
}
}
function uploadImage() {
var smallImage = document.getElementById('cameraImage');
if (smallImage.src && smallImage.src !== "") {
var f = new FileTransfer();
f.upload(
// file path
smallImage.src,
// server URL - update to your own, and don't forget to
// include your domain in an access element in config.xml
"http://192.168.1.91/upload.php",
// success callback
function(result) {
document.getElementById('uploadProgress').innerHTML =
result.bytesSent + ' bytes sent';
alert(result.responseCode + ": " + result.response);
},
// error callback
function(error) {
alert('error uploading file: ' + error.code);
},
// options
{ fileName: 'myImage.jpg',
params: { 'username':'jtyberg' }
});
}
}
The server Id above is correct (it is the proper translation of my own development server so I am not using localhost, as I need this to be accurate). Everything you see with the exception of the server IP is vanilla, out the box, unaltered working example from phonegap. The phone is one the same 192 network and defintaly tries to run whatever upload.php I try
Basically I want to take this file, and using the upload.php file move it to
http : // 192.168.1.91/injury/sample_images/xxxx.jpg (spacing http as not sure how to stop it linking)
I have checked rights they are all ok, and my config.html has allow all domains
can anyone please put me out my misery and give me an example upload.php that will use the upload code above and just do something with the camera image.
Once I can get a working example, I can break down exactly what is happening and start the learning process.
Alternativly if someone can provide a working app.. with both app and server side code to use as a tutorial, I am happy to do the studying involved.
Many many thanks in advance for any time people give to this. I am at my wits end, and getting myself in a right muddle when I should be able to get this done.
I decided to use a posting method of the base64 string. I did find however that in this case it was more likely to be the settings on my development server that were the likely cause.

HTML 5 Drag & Drop upload with jQuery and PHP

I'm currently following this example for HTML 5 drag and drop. I am hoping to use this to upload the dropped files to a remote FTP server with a php script. However, how do my php script access these dropped files ?
With a regular web form, I can use $_FILES.. But I don't suppose I can use $_FILES for the dropped files..
On the example, the script calls handleFiles function after a drop event
function handleFiles(files) {
var file = files[0];
document.getElementById("droplabel").innerHTML = "Processing " + file.name;
var reader = new FileReader();
// init the reader event handlers
reader.onprogress = handleReaderProgress;
reader.onloadend = handleReaderLoadEnd;
// begin the read operation
reader.readAsDataURL(file);
}
I guessing that I can iterate each element of the array list, and send each element to my php script. As I've mentioned above, how can I send this element from the array list to the php script? JSON ? jQuery POST ?
I am aware that there are various jquery plugins available to achieve this, and I have downloaded a few of them... However I'm just curious to know if I can implement the same thing with this example.
I presume by upload you mean upload it in a ajax operation.
file refer to a File object, which is available for you after the user had drop the file. After that you have two options:
Read the file using FileReader, send the text in xhr as post data (not recommend as it only work with text)
Pass the object to FormData then pass the FormData object to xhr to send the file (Doesn't work with Firefox <= 3.6 though)
Check Mozilla Developer Center document for the usage of these interfaces. I have working projects that use these objects, however there are too much bridging code to be a good walk-through demo. https://github.com/timdream/html5-file-upload
Why not use an open source solution for your problem rather than re-inventing the wheel.
http://plupload.com/
Is pretty much all you will ever need. I use it and it works wonders. Also, it falls back onto html 4 form uploading when a browser cannot handle html5.

Creating a custom upload progress bar

I have seen all the upload progress bar plugins, widgets, etc. – they all suck. They're either too bulky with too much useless code or they don't work.
What I want to know is where I can read up on how to display an easy upload progress indicator. Most browsers have a status progress bar on them below, but it isn't very professional to use just that when dealing with clients.
How does the browser do it? I want to know the internals of how the browser works with for indicating the status of something uploading so that maybe I can make something using PHP & jquery.
Thanks.
Since you want to use PHP, I'd start with the uploadprogress extension (PHP doesn't, by default, give you any data about until the upload is completed; this extension provides such server-side functionality). Note that it requires PHP 5.2+ and can be picky about configuration options. Also see its commentary and demo and troubleshooting hints). A short overview available in PHP documentation comments.
Using the extension, you can get some stats on the upload; then you can poll the server through AJAX and update some sort of progress bar.
To be a bit more specific:
get an unique identifier for the form, and include it in a hidden field
the upload should run in an IFRAME - some browsers won't allow DOM updates to the same page that is running the upload
poll the server via AJAX (using the identifier to specify which upload you're interested in) and parse the result (IIRC, you'll get something like "bytes_uploaded => 123, content-length=> 1000")
update your progress bar (the way you display it is up to you, I use "x% done" plus a graphical bar)
redirect whole page when form uploaded OK
(Oh, and btw, check PHP's upload_max_filesize and post_max_size settings, as both limit the maximum upload size)
There is no reliable method to get the progress of a file upload using JavaScript. Support for the XMLHttpRequest upload.onprogress event is missing in many browsers, even with HTML5, you will inevitably need to turn to Flash, or another method of file upload.
After asking this question, I eventually settled on using plupload for my uploading needs.
Javascript/Ecmascript cannot mess with native browser functionalitys (which uses C/C++ mostly along with OS APIs which access TCP/UDP sockets.
To display a progressbar with JS you need serverfeedback. That can be accomplished by using a server polling like COMET for instance.
But at this point, it's never that accurate like the browser buildin progressbar. It will change maybe with HTML5 WebSockets.
To have an accurate result, you need a continuous connection. You can fake and gild the client-server request delay, but it's still there. I don't know exactly how Flash handles this issues, but I guess it also does not have connection-oriented stream (Correct me if I'm wrong here).
I know this isnt what you're looking for but I've been using plupload for uploads recently and it seems pretty good plus doesnt rely on flash or html5 exclusively
example:
the url is the proccessing page (php
file)
container = the parent div or form that that the upload button lives in (its really important to set this - there are some example of how you can attach things to certain actions that plupload does. for example below you can see i have attached uploader.start();to the uploader.start(); hook.
you should also be able to see how i've made a custom upload progress bar, by attaching to the upload progress hook
worth asking questions on the forum on the plupload site if you get stuck, they're good at answering them!
$(function(){
//plupload
var uploader = new plupload.Uploader({
runtimes : 'gears,html5,flash',
browse_button : 'pickfiles',
container : 'form_2',
max_file_size : '10mb',
url : '<?php echo SITE_ROOT ?>plupload/upload.php',
//resize : {width : 320, height : 240, quality : 90},
flash_swf_url : '<?php echo SITE_ROOT ?>plupload/js/plupload.flash.swf',
filters : [
{title : "Image files", extensions : "jpg,gif,png"}
]
});
uploader.init();
uploader.bind('FilesAdded', function(up, files) {
uploader.start();
});
uploader.bind('UploadProgress', function(up, file) {
if(file.percent < 100 && file.percent >= 1){
$('#progress_bar div').css('width', file.percent+'%');
}
else{
$('#progress_bar').fadeOut(600);
}
});

Categories