Skip to content
A visual single file uploader with same page thumbnail viewer and Editor
PHP
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
media
upload image
LICENSE
README.md
index.php

README.md

PHP and Javascript /JQuery Image File Uploader with Thumbs Viewer /Editor

Background

Uploading a file is relatively easy. However to create a seamless user experience can be difficult. So I went ahead and created a visual single file uploader with same page thumbnail editor.

Project Scope

  • A consistently styled, input with dynamic status with an integrated button (file open browser).

  • Upload all normal formats such as "jpg", "png", "gif", "bmp", "jpeg", "GIF", "JPG", "PNG".

  • Provide ability to change the image name before uploading.

  • Preview a selected thumbnail image before uploading

  • Show image uploading progress.

  • Auto adjust ant uploading file format to a standard “.png” format to reduce unnecessary overhead without reducing image quality.

  • Ensure that the file has a unique name to prevent overwriting an existing file.

  • Limit the size of the file to 2 MB.

  • Provide an integrated thumbnail viewer which also auto updates on uploaded completion.

Provide ability to re-edit the name or delete the image.

  • Must simply work in the webserver.

Coding Difficulty

Medium. Good knowledge of Javascript/Ajax and PHP required would help.

Libaries

**Bootstrap 3 Framework –**download here or visit the website at http://getbootstrap.com.

Bootstrap Filestyle – download the bootstrap-filestyle.min.js from here or visit the website at http://markusslima.github.10/bootstrap-Filestyle.

This improves on the poorly styled Bootstrap input implementation. The Bootstrap Filestyle JQuery based plugin is simple and efficient and is a nicely styled input/button. Check the site out to view all the options offered. This plugin requires JQuery to create the styling and function.

JQuery – download from here or visit the website http://jquery.com.

View Working Example

View Example

Structure

The file structure is as follows. The folder uploads holds no script but is the folder where all the uploaded images are stored.

Create file Index.php

Index.php

<!--We can now add the Html to the file -->

<!DOCTYPE html>

<html>

<head>

<title>Upload an image < 2mb and resizes large file to web friendly size</title>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link href="css/bootstrap.min.css" rel="stylesheet">

<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>

<script type="text/javascript" src="js/bootstrap.min.js"></script>

<script type="text/javascript" src="js/bootstrap-filestyle.min.js"></script>

</head>

<body>

<div class="container">

<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">

<h3>Upload an image <small> < 2mb (auto-resizes images) </small></h3>

<hr>

<form id="myform" method="post">

<div class="form-group">

<!—This adds the input for the change of file name

<input class="form-control input" type="text" id="filename" placeholder =

"Enter New filename for image" >

</div>

<!—this is the filestyle plugin code which calls the Javascript to open the file browser referred to below.-->

<div class="form-group">

<input class="form-control input" type="file" id="myfile" onchange="readURL(this);">

</div>

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">

<div class ="row">

<div class="col-xs-3 col-sm-3 col-md-3 col-lg-3">

<div class="form-group">

<img src="img/preview.png" alt="my image" id = "img_prev" width = "140" class="img-responsive" >

</div>

</div>

<div class="col-xs-9 col-sm-9 col-md-9 col-lg-9">

<div class="progress">

<div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%,margin:100px;">0%</div>

</div>

<div class="msg">

</div>

<br>

<button inputtype="Upload" type="button" id="btn" class="btn btn-success" value="Upload" ><i class="glyphicon glyphicon-new-window "></i> Upload </button>

</form>

</div>

</div>

</div>

<hr>

<h3 > Image Folder <small> click on image to edit / delete</small></h3>

<hr>

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">

<div class ="row">

<script>

This script open the computors’ file explorer.

function readURL(input) {

if (input.files && input.files[0]) {

var reader = new FileReader();

reader.onload = function (e) {

$('#img_prev')

.attr('src', e.target.result)

};

reader.readAsDataURL(input.files[0]);

}

}

function clearimage(){

$('#img_prev')

.attr('src', "img/preview.png")

}

This clears any information left in the input areas and uses a timer to reset the progress bar.

Function clearinput(){

$('form').find('input[type=text],input[type=file],textarea').val('');

}

function resettimer() {

$('.myprogress').text('0%');

$('.myprogress').css('width', '0%');

$('.msg').text('Ready to Upload a New image... ');

clearinput();

clearimage();

location.reload();

}

$(function () {

$('#btn').click(function () {

$('.myprogress').css('width', '0');

$('.msg').text('');

var filename = $('#filename').val();

var myfile = $('#myfile').val();

if (filename == '' || myfile == '') {

alert('Please enter file name and select file');

return;

}

This is used to change the filename of the file to be uploaded.

var formData = new FormData();

formData.append('myfile', $('#myfile')[0].files[0]);

formData.append('filename', filename);

$('#btn').attr('disabled', 'disabled');

$('.msg').text('Uploading in Progress...');

This is the AJAX code to POST (send) the file information to the server as all the action has taken place directly on the web-browser. It also communicates to the progress bar. The eventlistener is attached to the upload and any changes of the XMLHttpRequest() of data sent in the background to the uploadscript.php will communicate the loaded information which will continually recalculate the percentage complete. The progressbar is then refreshed.

$.ajax({

url: 'uploadscript.php',

data: formData,

processData: false,

contentType: false,

type: 'POST',

// 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) {

$('.msg').text(data);

$('#btn').removeAttr('disabled');

setTimeout(resettimer, 3000);

}

});

});

});

</script>

This script below is used to change the input text to inform you of two different statuses. It will inform when a new image can be uploaded.

<script type="text/javascript">

$('#myfile').filestyle({

buttonName : 'btn-warning ',

buttonText : " &nbsp; Select an Image to Upload "

});

$('.msg').text('Ready to Upload a New Image...');

</script>

On the php server side we create fileuploadscript.php

fileuploadscript.php

<?php

This file receives the AJAX POST call and receives the data so long as the data is not empty -“if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") “

We first check if the file is less than 2 MB and if it is then changes the name by using a count in date seconds which is added to the existing name i.e. box will become box03 . This ensures that no similar file name is overwritten.

We also resize the image to a max width of 800px and create a temporary copy which becomes a PNG file. The old file is deleted.

The file is now saved to the correct folder in the server.

error_reporting(0);

if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {

$path = "uploads/"; //set your folder path

//set the valid file extensions

$valid_formats = array("jpg", "png", "gif", "bmp", "jpeg", "GIF", "JPG", "PNG");//add the formats you want to upload add if needed "doc", "txt", "docx", "pdf", "xls", "xlsx")

$name = $_FILES['myfile']['name']; //get the name of the file

$size = $_FILES['myfile']['size']; //get the size of the file

if (strlen($name)) { //check if the file is selected or cancelled after pressing the browse button.

list($txt, $ext) = explode(".", $name); //extract the name and extension of the file

if (in_array(strtolower($ext), $valid_formats)) { //if the file is valid go on.

if ($size < 2098888) { // check if the file size is more than 2 mb

$file_name = $_POST['filename']; //get the file name

/* changename add int seconds to name to create unique name*/

$tmpint =idate('s');

$file_name = $file_name.''.$tmpint;

$tmp = $_FILES['myfile']['tmp_name'];

/* resize image and change to png */

$maxDim = 800;

list($width, $height, $type, $attr) = getimagesize($tmp );

if ( $width > $maxDim || $height > $maxDim ) {

$target_filename = $tmp;

$fn = $tmp;

$size = getimagesize( $fn );

$ratio = $size[0]/$size[1]; // width/height

if( $ratio > 1) {

$width = $maxDim;

$height = $maxDim/$ratio;

} else {

$width = $maxDim*$ratio;

$height = $maxDim;

}

$src = imagecreatefromstring( file_get_contents( $fn ) );

$dst = imagecreatetruecolor( $width, $height );

imagecopyresampled( $dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1] );

imagedestroy( $src );

imagepng( $dst, $target_filename ); // adjust format to png

imagedestroy( $dst );

$ext ='png';

}

else{ //change to png format

list($width, $height, $type, $attr) = getimagesize($tmp );

$target_filename = $tmp;

$fn = $tmp;

$size = getimagesize( $fn );

$src = imagecreatefromstring( file_get_contents( $fn ) );

$dst = imagecreatetruecolor( $width, $height );

imagecopyresampled( $dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1] );

imagedestroy( $src );

imagepng( $dst, $target_filename ); // adjust format to png

imagedestroy( $dst );

$ext ='png';

}

/*end resize image and change to png */

// if (move_uploaded_file($tmp, $path . $file_name.'.'.$ext)) { //use if not resizing image or file

if (move_uploaded_file($target_filename, $path . $file_name.'.'.$ext)) { //check if it the file move successfully.

echo "Image Uploaded Successfully...";

} else {

echo "failed";

}

} else {

echo "File size exceeds the max 2 MB...";

}

} else {

echo "Invalid file format...";

}

} else {

echo "No File Selected...!";

}

exit;

}

$path = '';

$name = '';

?>

Create a file imageadjust.php.

imageadjust.php

This file allows the thumbnails to be deleted and also allows the filename to be changed.

If deleted, the thumbnail will immediately be removed in the Index.php file.

This file will open with an input with the existing filename. Changing the input name and posting the data results in the filename being changed.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link href="css/bootstrap.min.css" rel="stylesheet">

<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>

<script type="text/javascript" src="js/bootstrap.min.js"></script>

<script type="text/javascript" src="js/bootstrap-filestyle.min.js"></script>

</head>

<body>

<div class="container">

<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">

<?php

$path = "uploads/"; //set your folder path

//delete file and edit file folder

//error_reporting(0);

$id = null;

if ( !empty($_GET['id'])) {

$oldname = $_REQUEST['id'];

//echo $oldname;

}

if ( $id==null) {

// header("Location: index.php");

}

if(isset($_POST['submit'])){

$newname = $_POST['name'];

// echo $newname;

echo $path.''.$newname;

rename ($path.''.$oldname , $path.''.$newname);

header("Location: index.php");

// $oldname =$newname;

}

?>

<h3>Edit Selected Image </h3>

<hr>

<form method="post" enctype="multipart/form-data" >

<div class="form-group">

<input class="form-control input" name = "name" type="text" id="filename" placeholder = "Enter New filename for image" value="<?php echo $oldname;?>">

</div>

<div class="form-actions">

<button inputtype="submit" class= "btn btn-success" name="submit" value="submit"><i class="glyphicon glyphicon-check "></i></button>

</div>

</form>

</div>

<?php

?>

</body>

</html>

Author

Greg Bayes - Bayesean Blog.

https://www.bayeseanblog.com.

License

This project is licensed under the MIT license agreement.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Acknowledgments

Thank you to Bootstrap Filestyle .

You can’t perform that action at this time.