I have a upload button on my webpage. Whenever I upload an image it will show a preview of the image(s) that were uploaded. If more than one image is uploaded, the previews of the second image will be shown next to the first and so on.
I need to be able to upload all the shown images into my uploads folder using PHP. How can I do this?
This is my HTML code that will upload the images one by one and show preview:
<html>
<head>
<meta charset=utf-8 />
<title>Image preview</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
var blank = "http://upload.wikimedia.org/wikipedia/commons/c/c0/Blank.gif";
</script>
<style>
img {
height:200px ! important;
width:200px ! important;
}
</style>
<script type="text/javascript">
//<![CDATA[
$(window).load(function() {
$('input[type="file"]').change(function() {
if ($(this).val() !== "") {
var file = $('#file_select')[0].files[0];
console.log(file.size);
//console.log(file.width);
var reader = new FileReader();
var img = new Image();
var _URL = window.URL || window.webkitURL;
reader.readAsDataURL(file);
reader.onload = function(_file) {
// Create a container for image and span X
$imageItem = $('<div style=" float: left; border:5px solid gray; ">').addClass('imageItem');
$(img).appendTo($imageItem);
$('<span>').html('<a href="#" style=" z-index: 1; margin-left: -32px;"><img src="trash.png" title="remove" style=" width: 32px ! important;height: 32px ! important;">
</a>').addClass('remover').appendTo($imageItem);
img.src = _file.target.result;
// Append the container to panel
$('#previewPane').append($imageItem);
//console.log(img.src);
console.log(img.width);
}
}
// Deletegate for dynamically created span, so we don't have to register a
// new event listener each time a new imageContainer is created.
$('#previewPane').on('click', '.remover', function() {
$this = $(this);
$this.parent('.imageItem').remove();
});
});
}); //]]>
</script>
</head>
<body>
<section>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type='file' name="file[]" id="file_select" multiple="multiple" />
<br/> <span id="previewPane"></span>
<input type="submit" value="OK">
</form>
</section>
</body>
</html>
This is my PHP code but currently it is uploading only one image.
<?php
for($i=0; $i<count($_FILES['file']['name']); $i++) {
$tmpFilePath = $_FILES['file']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "uploads/" . $_FILES['file']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
}
}
}
?>
Related
I have sucessfully created a website that used the https://github.com/BossBele/cropzee library.
I have created a HTML form that takes inn a image from the user:
When the user has selected a image the Cropzee.js sucessfully loads and I can rotated/crop the image as expected:
Now I have the button Get Image (as blob / data-url) that gives me a alert box with a base64 image:
<button onclick="alert(cropzeeGetImage('cropzee-input'))">Get Image (as blob / data-url)</button>
I need to somehow send the base64 blob / data-url / image to my backend, I use PHP.
My HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cropzee jQuery PHP</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0;"/>
<!-- jQuery + cropzee.js -->
<script type="text/javascript" src="javascripts/jquery/jquery.min.js"></script>
<script src="javascripts/cropzee/cropzee.js" defer></script>
<!-- //jQuery + cropzee.js -->
<!-- CSS -->
<style>
.image-previewer {
height: 300px;
width: 300px;
display: flex;
border-radius: 10px;
border: 1px solid lightgrey;
}
</style>
<!-- //CSS -->
</head>
<body>
<h1>Upload</h1>
<!-- cropzee upload form -->
<label for="cropzee-input" class="image-previewer" data-cropzee="cropzee-input"></label>
<input id="cropzee-input" type="file" name="cropzee-input" accept="image/*">
<button onclick="alert(cropzeeGetImage('cropzee-input'))">Get Image (as blob / data-url)</button>
<script>
$(document).ready(function(){
if (window.location.href.indexOf("#") > -1) {
window.location = window.location.href.replace('#', '');
}
$("#cropzee-input").cropzee({startSize: [85, 85, '%'],});
});
</script>
<!-- //cropzee upload form -->
</body>
</html>
I have done this working to save the cropped image via Ajax Post to my PHP/MySQL backend.
Put a button to trigger the Ajax Call - like below
`<input type="button" onclick="uploadEx()" value="Upload" />`
Create a from with a hidden input - like below
`<form method="post" accept-charset="utf-8" name="form1">
<input name="hidden_data" id='hidden_data' type="hidden"/>
</form>`
Now put the Ajax call jQuery - like below
function uploadEx() {
var canvas = document.getElementById("cropzee-input");
var dataURL = canvas.toDataURL("image/jpeg");
document.getElementById('hidden_data').value = dataURL;
var fd = new FormData(document.forms["form1"]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload_data.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + '% uploaded');
alert('Succesfully uploaded');
} else {
alert('Captured data');
}
};
xhr.onload = function() {
};
xhr.send(fd);
};
```
Lastly the PHP file upload_data.php looks like below
`
$upload_dir = "uploaded_files/profile_pictures/";
$img = $_POST['hidden_data'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".jpeg";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.'; `
I want to do the following: after an user uploads 2 pictures I want to log a message that the process was completed so I can do something else afterwards. Here is a fiddle: https://jsfiddle.net/al21al/ms3ogck2/8/
My html is here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container-fluid slide2-img">
<p>Click on the "Choose file" button to upload a picture:</p>
<div class="uploadbuttons">
<form class="" action="/action_page.php">
<input type="file" id="picture1">
<div id="appendimg1"></div>
</form>
<form class="" action="/action_page.php">
<input type="file" id="picture2">
<div id="appendimg2"></div>
</form>
</div>
</div>
</body>
</html>
My js:
function doImage1() {
var image1, imgId1;
const fileSelector1 = document.getElementById('picture1'); //get first input
fileSelector1.addEventListener('change', function() { //read the image
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) { //call function to create img and append it
image1 = '<img src="' + e.target.result + '" style="width:200px;height:auto;" id="' + 'image1-morph">';
$("#appendimg1").empty().append(image1);
imgId1 = image1.split('id="').pop().replace('">', '');
console.log('1st img id', imgId1);
};
reader.readAsDataURL(this.files[0]);
}
});
}
function doImage2() {
var image2, imgId2;
const fileSelector2 = document.getElementById('picture2'); //get 2nd input
fileSelector2.addEventListener('change', function() { //read the image
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) { //call function to create img and append it
image2 = '<img src="' + e.target.result + '" style="width:200px;height:auto;" id="' + 'image2-morph">';
$("#appendimg2").empty().append(image2);
imgId2 = image2.split('id="').pop().replace('">', '');
console.log('2nd img id', imgId2);
};
reader.readAsDataURL(this.files[0]);
}
});
}
doImage1();
doImage2();
// how to wait till both images have been uploaded and then execute other code?
alert('both images have been uploaded');
// other code (...)
CSS:
.slide2-img form {
float: left;
}
Now it alerts me before both pictures have been uploaded (the alert shows right after the page render). I've been trying to use async await but to no avail. Could somebody help me please?
I suggest DRY - Don't Repeat Yourself
Here I count the number of images in the div and delegate the change from that div
$(".uploadbuttons").on("change", function(e) {
const tgt = e.target;
if (tgt.type !== "file") return;
if (!tgt.files || !tgt.files[0]) return
const reader = new FileReader();
const idx = tgt.id.replace("picture", "");
reader.onload = function(e) {
const image = `<img src="${e.target.result}" style="width:200px;height:auto;"
id="image${idx}-morph">`;
$("#appendimg"+idx).html(image);
console.log('img', idx);
if ($(".uploadbuttons").find("img").length===2) console.log("Both uploaded")
};
reader.readAsDataURL(tgt.files[0]);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="container-fluid slide2-img">
<p>Click on the "Choose file" button to upload a picture:</p>
<div class="uploadbuttons">
<form id="uploadForm" action="/action_page.php">
<input type="file" id="picture0">
<div id="appendimg0"></div>
<input type="file" id="picture1">
<div id="appendimg1"></div>
</form>
</div>
</div>
</body>
</html>
I have a button called f1 and I want it to display the value of the image that the user puts when they select an image. For example, when you select an image it'll display on the screen but I also want it to display on the button with proper width and height attributes, how would I do that? I've tried the document.getElementById("f1").innerHTML = input.value; but that only displays the file path, not the actual image. I appreciate the help.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img')
.attr('src', e.target.result)
.width(250)
.height(200);
};
reader.readAsDataURL(input.files[0]);
const f1 = document.getElementById("f1").innerHTML = input.value;
}
}
#f1 {
width:50px;
height:40px;
}
#img {
position:relative;
left:275px;
top:200px;
}
<!DOCTYPE html>
<html>
<head>
<title>Filter Image</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input type='file' id="file" onchange="readURL(this);" accept="image/gif, image/jpeg, image/png">
<img id="img"/>
<button id = "f1"></button>
</body>
</html>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img')
.attr('src', e.target.result)
.width(50)
.height(50);
};
reader.readAsDataURL(input.files[0]);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Filter Image</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<input type='file' id="file" onchange="readURL(this);" accept="image/gif, image/jpeg, image/png">
<button id = "f1"><img id="img"/></button>
</body>
</html>
here's my html with javascript using webcam.js. I just followed the https://github.com/jhuckaby/webcamjs on how you will implement it using existing form.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
Webcam.snap( function(data_uri) {
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('mydata').value = raw_image_data;
document.getElementById('myform').submit();
} );
</script>
<!-- A button for taking snaps -->
<form id="myform" method="post" action="myscript.php">
<input id="mydata" type="hidden" name="mydata" value=""/>
<input type=button value="Take Snapshot" onClick="take_snapshot()">
<input type="submit" value="submit">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
} );
}
</script>
here's the myscript.php to save the image. I successfully save the PATH in the database but I'm getting a corrupted .jpg file (file size always in 7 bytes).
<?php
include 'connect.php';
$encoded_data = $_POST['mydata']; // to get the base 64 code image link
$name = base64_decode($encoded_data); // to convert base 64 code
$name = date('YmdHis');
$newname="images/".$name.".jpg";
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
print "Error occured here";
exit();
}
else
{
$sql="INSERT INTO image (images) VALUES('$newname')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";
?>
After all the trail and errors i found out you'll need to convert the base64 string to a blob and then attach to a file before sending.
var binaryImg = atob(base64string);
var length = binaryImg.length;
var ab = new ArrayBuffer(length);
var ua = new Uint8Array(ab);
for (var i = 0; i < length; i++) {
ua[i] = binaryImg.charCodeAt(i);
}
var blob = new Blob([ab], {
type: "image/jpeg"
});enter code here
var imgFile = new File([blob], 'photo.jpeg', {type: 'image/jpeg'});
Now you can use the imgFile to send across to a remote server.
When the page is loaded, the image specified in src is displayed.When a user clicks on the form to upload the image,everything works fine except the image on the page does not change.
It is because when the user clicks on the form to upload the image, he is directed to php file 2 but from there there is no request to change the image in php file 1. How can I achieve this (using ajax and jquery)?
Try this code. This is the core.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#imgInp').on('change', function() {
readPath(this);
});
});
function readPath(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>
</head>
<body>
<form id="form1">
<input type='file' id="imgInp" />
<img id="blah" src="#" width="500px" height="200px" alt="your image" />
</form>
</body>
</html>
Here is another code snippet. Check your conditions in the server part and don't forget provide the locations correctly in server side and image src.
HTML Part
<!doctype html>
<head>
<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>
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>Ajax File Upload Demo</h1>
<img id="blah" src="#" width="500px" height="200px" alt="your image" />
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#blah").attr("src",response.responseText);
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
</body>
</html>
Upload.php
<?php
//upload.php
$output_dir = "C:/wamp/www/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
echo $_FILES["myfile"]["name"];
}
}
?>