How to preview an image before and after upload? - php

I am going to preview an image or photo in a form, but it doesn't work and the HTML code looks like this as below:
<form action="" method="post" enctype="multipart/form-data" name="personal_image" id="newHotnessForm">
<p><label for="image">Upload Image:</label>
<input type="file" id="imageUpload"/></p>
<p><button type="submit" class="button">Save</button></p>
<div id="preview">
<img width="160px" height="120px" src="profile pic.jpg" id="thumb" />
</div>
</form>
and incorporated JS code/script below:
<script type="text/jaavascript">
$(document).ready(function(){
var thumb=$('#thumb');
new AjaxUpload('imageUpload',{
action:$('newHotnessForm').attr('action'),
name:'image',
onSubmit:function(file,extension){
$('#preview').addClass('loading');
},
onComplete:function(file,response){
thumb.load(function(){
$('#preview').removeClass('loading');
thumb.unbind();
});
thumb.attr('src',response);
}
});
});
There are 2 main questions on my form:
1. Why doesn't the preview of the image or picture work?
2. How to paste the photo from the form when the save button is clicked, it will go/link to another PHP or PHP page that I created?

Try this: (For Preview)
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<body>
<form id="form1" runat="server">
<input type="file" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
Working Demo here>

meVeekay's answer was good and am just making it more improvised by doing 2 things.
Check whether browser supports HTML5 FileReader() or not.
Allow only image file to be upload by checking its extension.
HTML :
<div id="wrapper">
<input id="fileUpload" type="file" />
<br />
<div id="image-holder"></div>
</div>
jQuery :
$("#fileUpload").on('change', function () {
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
var image_holder = $("#image-holder");
image_holder.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});

On input type=file add an event onchange="preview()"
For the function preview() type:
thumb.src=URL.createObjectURL(event.target.files[0]);
Live example:
function preview() {
thumb.src=URL.createObjectURL(event.target.files[0]);
}
<form>
<input type="file" onchange="preview()">
<img id="thumb" src="" width="150px"/>
</form>

#######################
### the img page ###
#######################
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#f').live('change' ,function(){
$('#fo').ajaxForm({target: '#d'}).submit();
});
});
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
<input type="file" name="f" id="f" value="start upload" />
<input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>
#############################
### the nextimg page ###
#############################
<?php
$name=$_FILES['f']['name'];
$tmp=$_FILES['f']['tmp_name'];
$new=time().$name;
$new="upload/".$new;
move_uploaded_file($tmp,$new);
if($_FILES['f']['error']==0)
{
?>
<h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
}
?>

function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#ImdID').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
img {
max-width: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='file' onchange="readURL(this);" />
<img id="ImdID" src="" alt="Image" />

Related

rename an file on local disk using PHP or Javascript

I have a scenario in which user is prompted for selecting a file from local disk (an image). Upon selection, this image is shown in browser (without uploading). After seeing the image user inputs a number in CN No field. Upon submit I want to rename the file on local disk with the number input by user. Is there some way to do this in code using PHP or Javascript?
<html>
<head>
<script type='text/javascript'>
function preview_image(event)
{
var reader = new FileReader();
reader.onload = function()
{
var output = document.getElementById('output_image');
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
}
</script>
</head>
<body>
<form>
Select File: <input type="file" accept="image/*" onchange="preview_image(event)"> <br>
Enter CN No. <input type="number" id="cnno" name="cnno"> <br>
<input id="sbt" type="submit" name="submit" value="Submit" accesskey="u"> <br>
</form>
<img id="output_image" style="width: 400px"/>
</body>
</html>
You could do this, presuming downloading the file is ok.
<html>
<head>
<script type='text/javascript'>
var img;
function preview_image(elm) {
var reader = new FileReader();
reader.onload = function(event) {
img = event.target.result
document.getElementById("image_preview").src = img;
};
reader.readAsDataURL(elm.files[0]);
}
function download() {
var element = document.createElement('a');
element.setAttribute('href', img)
element.setAttribute('download', document.getElementById("cnno").value+'.png');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
</script>
</head>
<body>
Select File: <input type="file" accept="image/*" onchange="preview_image(this)"> <br>
Enter CN No. <input type="number" id="cnno" name="cnno"> <br>
<input id="sbt" type="submit" name="submit" value="Submit" accesskey="u" onclick="download()"><br>
<img id="image_preview" style="width: 400px"/>
</body>
</html>
try this:
var file = document.GetElementById('fileupload1');
var blob = file.files[0].slice(0, -1, 'image/png');
newFile = new File([blob], 'name.png', {type: 'image/png'});
But its only for image rename.

How to select area of an image for cropping?

I am working on image cropping in PHP Codeigniter, below is my code that I have tried. When I gave the path of the image, the code worked fine, means I can select the area of the image to crop. But when I tried the same code with user uploaded image( user upload image and then crop), I cannot select image area of uploaded image. How to select image area of an image uploaded by user? I am using JCrop plugin.
imagecrop
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
<title>Jcrop Dynamic Avatar JS/PHP Demo</title>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link rel="stylesheet" type="text/css" href="css/jquery.Jcrop.css">
<script type="text/javascript" src="js/jquery.Jcrop.js"></script>
<script type="text/javascript" src="js/cropsetup.js"></script>
</head>
<body>
<div id="wrapper">
<div class="jc">
<input type='file' name="userfile" size="20"
onchange="readURL(this);"/>
<img src="#" id="target" alt="[Jcrop Example]" />
<div id="preview-pane">
<div class="preview-container">
<img src="#" class="jcrop-preview" alt="Preview" />
</div>
</div>
<div id="form-container">
<form id="cropimg" name="cropimg" method="post" action="crop.php"
target="_blank">
<input type="hidden" id="x" name="x">
<input type="hidden" id="y" name="y">
<input type="hidden" id="w" name="w">
<input type="hidden" id="h" name="h">
<input type="submit" id="submit" value="Crop Image!">
</form>
</div>
</div>
</div>
<script>function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#target')
.attr('src', e.target.result)
.width(200)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}</script>
</body>
</html>
PHP code:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
if(!isset($_POST['x']) || !is_numeric($_POST['x'])) {
die('Please select a crop area.');
}
$src = 'images/cropimg.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor($targ_w, $targ_h);
imagecopyresampled($dst_r,$img_r,0,0,$_POST['x'],$_POST['y'],
$targ_w,$targ_h,$_POST['w'],$_POST['h']);
header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
exit;
}
?>
This is Javascript code:
$(function($){
var jcrop_api,
boundx,
boundy,
// Grab some information about the preview pane
$preview = $('#preview-pane'),
$pcnt = $('#preview-pane .preview-container'),
$pimg = $('#preview-pane .preview-container img'),
xsize = $pcnt.width(),
ysize = $pcnt.height();
$('#target').Jcrop({
onChange: updatePreview,
onSelect: updatePreview,
bgOpacity: 0.5,
aspectRatio: xsize / ysize
},function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
jcrop_api = this;
$preview.appendTo(jcrop_api.ui.holder);
});
function updatePreview(c) {
if (parseInt(c.w) > 0) {
var rx = xsize / c.w;
var ry = ysize / c.h;
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
$pimg.css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
}
});
The jQuery pluging ImageSelectArea worked for me !
http://odyniec.net/projects/imgareaselect/
Code is provided below:
<html>
<link rel="stylesheet" href="css/imgareaselect.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/jquery.imgareaselect.js"></script>
<body>
<form action="crop.php" method="post" enctype="multipart/form-data">
Upload Image: <input type="file" name="image" id="image" />
<input type="hidden" name="x1" value="" />
<input type="hidden" name="y1" value="" />
<input type="hidden" name="w" value="" />
<input type="hidden" name="h" value="" /><br><br>
<input type="submit" name="submit" value="Submit" />
</form>
<p><img id="previewimage" style="display:none;"/></p>
</body>
<script>
jQuery(function($) {
var p = $("#previewimage");
$("body").on("change", "#image", function(){
var imageReader = new FileReader();
imageReader.readAsDataURL(document.getElementById("image").files[0]);
imageReader.onload = function (oFREvent) {
p.attr('src', oFREvent.target.result).fadeIn();
};
});
$('#previewimage').imgAreaSelect({
onSelectEnd: function (img, selection) {
$('input[name="x1"]').val(selection.x1);
$('input[name="y1"]').val(selection.y1);
$('input[name="w"]').val(selection.width);
$('input[name="h"]').val(selection.height);
}
});
});
</script>
</html>

Multiple images uploading is not working multiple times in a page

I am trying to edited multiple images upload in more than once.
But is not working.Please update any suggestions or answer.
Below sample code:
<div id="upload_form" class="hide">
<form action="multi_files.php" target="hidden_iframe" enctype="multipart/form-data" method="post">
<input type="file" multiple name="upload_files[]" id="upload_files">
</form>
</div>
<div align="center" style="padding:10px">
<button onclick="Uploader.upload();" class="btn btn-primary btn-lg">Upload Files</button>
<div id="wait" class="hide"><img src="upload-indicator.gif" alt=""></div>
</div>
<div>
<iframe name="hidden_iframe" id="hidden_iframe" class="hide"></iframe>
</div>
<div id="uploaded_images" align="center">
</div>
Here I am add this code for another upload option with different form.
But is not working.Below the edited code:
<!--####### Below Edited as same on above #######-->
<div id="upload_form_cover" class="hide">
<form id="upload_form_cover" action="multi_files_cover.php" target="hidden_iframe" enctype="multipart/form-data" method="post">
<input type="hidden" name="image_type" value="cover_image" >
<input type="file" multiple name="upload_files_cover[]" id="upload_files_cover">
</form>
</div>
<div align="center" style="padding:10px">
<button onclick="Uploader_cover.upload();" class="btn btn-primary btn-lg">Upload Files TEST</button>
<div id="wait_cover" class="hide"><img src="upload-indicator.gif" alt=""></div>
</div>
JavaScript Code :
<script type="text/javascript">
var Uploader = (function () {
jQuery('#upload_files').on('change', function () {
jQuery("#wait").removeClass('hide');
jQuery('#upload_files').parent('form').submit();
});
var fnUpload = function () {
jQuery('#upload_files').trigger('click');
}
var fnDone = function (data) {
var data = JSON.parse(data);
if (typeof (data['error']) != "undefined") {
jQuery('#uploaded_images').html(data['error']);
jQuery('#upload_files').val("");
jQuery("#wait").addClass('hide');
return;
}
var divs = [];
for (i in data) {
divs.push("<div><img src='" + data[i] + "' style='height:100px' class='img-thumbnail'></div>");
}
jQuery('#uploaded_images').html(divs.join(""));
jQuery('#upload_files').val("");
jQuery("#wait").addClass('hide');
}
return {
upload: fnUpload,
done: fnDone
}
}());
<!--####### Belo Edited as same on above for form id: upload_form_cover #######-->
var Uploader_cover = (function () {
alert("Uploader_cover");
jQuery('#upload_files_cover').on('change', function () {
jQuery("#wait_cover").removeClass('hide');
jQuery('#upload_form_cover').submit();
});
var fnUpload = function () {
jQuery('#upload_files_cover').trigger('click');
}
var fnDone = function (data) {
var data = JSON.parse(data);
if (typeof (data['error']) != "undefined") {
jQuery('#uploaded_images_cover').html(data['error']);
jQuery('#upload_files_cover').val("");
jQuery("#wait_cover").addClass('hide');
return;
}
var divs = [];
for (i in data) {
divs.push("<div><img src='" + data[i] + "' style='height:100px' class='img-thumbnail'></div>");
}
jQuery('#uploaded_images_cover').html(divs.join(""));
jQuery('#upload_files_cover').val("");
jQuery("#wait_cover").addClass('hide');
}
return {
upload: fnUpload,
done: fnDone
}
}());
</script>
</body>
You are not submitting the right dom ie form in both functions. Put this.
jQuery('#upload_files').on('change', function () {
jQuery("#wait").removeClass('hide');
$(this).parent().submit();
});
First create a "arts" folder for putting image on it
index.html
<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="upl" multiple />
</form>
upload.php
<?php
$allowed = array('png', 'jpg', 'jpeg', 'gif', 'swf'); //The file you want to user put
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
$extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'arts/'.$_FILES['upl']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
?>

JQuery/PHP multiple files one at a time with only one input field

I search through the net but didn't find much things on my problem. Hope someone here can help!
As i write in the title I want to upload mutliple files, one at a time, with only one input.
I tried to do this using JQuery as you can see below, but obviously it doesn't work!
Anyone can help, please?
<!doctype html>
<html>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<head>
<script>
$(document).ready(function() {
$(document).on('change', '.file',function(){
$('<input type="file" name="file[]" class="file" size="60" />').appendTo($("#divAjout"));
$("div input:first-child").remove();
return false;
});
});
</script>
<title>test input file unique pour plusieurs fichiers</title>
</head>
<body>
<form action="" method="post" enctype='multipart/form-data'>
<div id="divAjout">
<input type="file" name="file[]" class="file" id='file' size="60" />
</div>
<input name="submit" type="submit">
</form>
<?php if(isset($_POST['submit'])){echo'<pre>'; print_r($_FILES);echo'<pre>';} ?>
</body>
</html>
You can clone input file with incrementing name attribute, like file[0], file[1], file[2], etc.
function readURL(input) {
var index = ($(input).data('index'));
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(input).parent().children('.newImage')
.attr('src', e.target.result)
.height(120);
};
reader.readAsDataURL(input.files[0]);
$('.addPh').show();
$('.addPh').last().clone().insertBefore($('#addPhoto')).hide();
++index;
$('.addPh').last().children('.photo_new').data('index', index).attr('name', 'photo_new['+index+']');
}
}
$(document).ready(function () {
$('#addPhoto').click(function () {
$('.photo_new').last().click();
});
});
See this example: https://jsfiddle.net/w0cd3Ls4/3/

How to interrupt a form submit and modify CSS class attributes

I currently have a form that is posting a file, however I want to interrupt the submit so I can display a 'loading' gif and then submit. That way the gif acts as a loading symbol for larger files. I need a way to change the css class attribute from display:none to display:all. Any help?
My code:
<html>
<head>
<title>Upload your media!</title>
<style type="text/css">
load {
display: none;
}
</style>
<script>
function validateForm()
{
var x=document.forms["mediaupload"]["title"].value;
if (x==null || x=="")
{
alert("Title must be filled out");
return false;
}
var y=document.forms["mediaupload"]["info"].value;
if (y==null || y=="")
{
alert("Description must be filled out");
return false;
}
var z=document.forms["mediaupload"]["file"].value;
if (z==null || z=="")
{
alert("You need to select a file to upload");
return false;
}
}
</script>
</head>
<body>
<h1>TOOB</h1>
<form name="mediaupload" action="upload_file.php" onsubmit="return validateForm()" method="post"
enctype="multipart/form-data">
<fieldset>
<legend><h4>Upload</h4></legend>
Title:<input type="text" name="title"><br>
Description:<textarea rows="10" cols="30" name="info">Write your desiption here</textarea><br>
Anonymous:<input type="checkbox" name="anonymous"><br>
File Upload:<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</fieldset>
</form>
<load><img id="loading" src="sitemedia/loading.gif" ></load>
</body>
</html>
use jQuery for this, remove the default submit and add timeout
$('form').submit(function(e)) {
e.preventDefault();
setTimeout(function() {
this.submit();
}, 5000); // in milliseconds
}
$("#form_id").submit(function(e){
e.preventDefault();
//Code for displaying the image
});
I was able to do this in pure javascript.
HTML
I changed the submit button to this:
<input type="button" onclick="loadFunc()" name="submit" value="Submit">
And added this loading div:
<div id="loading" style="display:none">
<img src="sitemedia/loading.gif" />
</div>
JavaScript
function loadFunc() {
document.getElementById("loading").style.display = "block";
document.mediaupload.submit();
}
See CodePen here.

Categories