Hi all you fantastic people. I'm a bit of a newbie on this.
I want to local select a file -> greyscale and downscale it (because it offen comes from a mobile devices) -> And then upload it to the ocr.space
Here is what I have so far on downscale:
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width=800
canvas.height=600
ctx.drawImage(img, 0, 0, 800, 600);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
<html>
<head>
<title>Upload PNG, JPG file</title>
</head>
<body>
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas" name="imageCanvas"></canvas>
</body>
</html>
How do I send it to OCR with the following code so far:
(My OCR code takes file input, but I have a canvas because I need to downscale it first).
<?php
if(isset($_POST['submit']) && isset($_FILES)) {
require __DIR__ . '/vendor/autoload.php';
$target_dir = "uploads/";
$uploadOk = 1;
$FileType = strtolower(pathinfo($_FILES["attachment"]["name"],PATHINFO_EXTENSION));
$target_file = $target_dir . generateRandomString() .'.'.$FileType;
// Check file size
if ($_FILES["attachment"]["size"] > 990000) {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, filen er desværre for stor";
$uploadOk = 0;
}
/*if($FileType != "png" && $FileType != "jpg") {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, det skal være en jpg, jpeg eller png fil";
$uploadOk = 0;
}*/
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_file)) {
uploadToApi($target_file);
} else {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, der skete en fejl da foto blev uploadet.";
}
}
} else {
header('HTTP/1.0 403 Forbidden');
echo "Beklager, venligst upload en fil";
}
function uploadToApi($target_file){
require __DIR__ . '/vendor/autoload.php';
$fileData = fopen($target_file, 'r');
$client = new \GuzzleHttp\Client();
try {
$r = $client->request('POST', 'https://api.ocr.space/parse/image',[
'headers' => ['apiKey' => 'xxxxxxxx'],
'multipart' => [
[
'name' => 'file',
'contents' => $fileData
]
]
], ['file' => $fileData]);
$response = json_decode($r->getBody(),true);
if($response['ErrorMessage'] == "") {
?>
<html>
<head>
<title>Result</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.min.js'></script>
</head>
<body>
<div class="form-group container">
<label for="exampleTextarea">Result</label>
<input type="text" id="nummerplade" name="nummerplade" value="<?php foreach($response['ParsedResults'] as $pareValue) {echo $pareValue['ParsedText'];}?>">
<textarea class="form-control" id="exampleTextarea" rows="30"><?php foreach($response['ParsedResults'] as $pareValue) {echo $pareValue['ParsedText'];}?></textarea>
</div>
</body>
</html>
<?php
} else {
header('HTTP/1.0 400 Forbidden');
echo $response['ErrorMessage'];
}
} catch(Exception $err) {
header('HTTP/1.0 403 Forbidden');
echo $err->getMessage();
}
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
I'm writing this answer to clarify how to apply the information referenced in my previous comment. You won't use the $_FILES variable at all. You will instead post your canvas as a data url in a normal variable through ajax and you will access it through the $_POST variable. Then you will process this data url to get the binary image and do everuting you want with it, i.e. save it to a file, post it to ocr service, etc.
The following code on the client side uses jquery, you have to download it in the same dir or replace the src attribute with a public available url (CDN):
<html>
<head>
<script src="jquery-3.6.0.min.js"></script>
<script>
$(function() {
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');
function handleImage(e) {
var reader = new FileReader();
reader.onload = function(event) {
var img = new Image();
img.onload = function() {
canvas.width=80
canvas.height=60
ctx.drawImage(img, 0, 0, 80, 60);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
$('#upload').click(function() {
var canvasData = canvas.toDataURL("image/png");
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: canvasData
}
}).done(function(o) {
alert('Image sent to the server');
});
});
});
</script>
</head>
<body>
<label>Image File:</label><br/>
<input type="file" id="imageLoader" name="imageLoader"/>
<canvas id="imageCanvas" name="imageCanvas"></canvas>
<button id="upload">Upload</button>
</body>
</html>
The php script should be like this:
<?php
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//... do anything you want with $fileData ...
?>
Related
For the project I am working on I am trying to get thumbnails generated when a video is uploaded. This is done by doing the following:
HTML Form:
<form action='videoUpload.php' id="videoUpload" method='post' enctype="multipart/form-data">
<input type='hidden' name='id' value='<?php echo $row['videoID'];?>'>
<p><label>Title</label><br />
<input type='text' name='videoTitle' required value='<?php if(isset($error)){ echo $_POST['videoTitle'];}?>'></p>
<p><label>Video</label><br />
<input type="file" name='video' id="video" class="video" required value='<?php if(isset($error)){ echo $_POST['video'];}?>'></p>
<input type="hidden" id="thumbnail" name="thumbnail" src="" >
<script src="thumbnail.js"></script>
<input type="hidden" name='videoDuration' id="videoDuration" required value='<?php if(isset($error)){ echo $_POST['videoDuration'];}?>'></p>
<div id="duration" name="duration">Please choose a video</div>
<script src="duration.js"></script>
<p><input type='submit' name='submit' id='submit' value='Submit'></p>
The JS file thumbnail.js is what I'm using to generate an image:
const thumbnail = document.querySelector('.video');
thumbnail.addEventListener('change', function(event) {
for (let i= document.images.length; i-->0;)
document.images[i].parentNode.removeChild(document.images[i]);
let file = event.target.files[0];
let fileReader = new FileReader();
if (file.type.match('image')) {
fileReader.onload = function() {
let img = document.createElement('img');
img.src = fileReader.result;
document.getElementsByTagName('div')[0].appendChild(img);
};
fileReader.readAsDataURL(file);
} else {
fileReader.onload = function() {
let blob = new Blob([fileReader.result], {type: file.type});
let url = URL.createObjectURL(blob);
let video = document.createElement('video');
let timeupdate = function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
video.pause();
}
};
video.addEventListener('loadeddata', function() {
if (snapImage()) {
video.removeEventListener('timeupdate', timeupdate);
}
});
let snapImage = function() {
let canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
let image = canvas.toDataURL();
console.log(image);
let success = image.length > 100000;
if (success) {
document.getElementById("thumbnail").src = image;
URL.revokeObjectURL(url);
}
return success;
};
video.addEventListener('timeupdate', timeupdate);
video.preload = 'metadata';
video.src = url;
// Load video in Safari / IE11
video.muted = true;
video.playsInline = true;
video.play();
};
fileReader.readAsArrayBuffer(file);
}
});
I am then trying to upload the image through my form by doing:
$target_dir = "../thumbnails/";
$target_file = $target_dir . basename($_FILES["thumbnail"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
//collect form data
extract($_POST);
$check = getimagesize($_FILES["thumbnail"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["thumbnail"]["size"] > 2000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["thumbnail"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
(there is more to the file but it's unnecessary to the question).
Now what I'm getting is errors saying that 'thumbnail' is undefined and I'm not sure why? Not sure where it is I've gone wrong with this, it seems that the image isn't getting passed through the form for some reason? Any help would be greatly appreciated
This JS creates a canvas and copy the video frame to it, than push the image visible on the canvas to the element's src attribute.
While it'll display an image in the browser, the input element will only send value attribute when sending the form.
See some other question with about the same conclusion:
How to replace a file input's content by the result of canvas.toDataURL?
I find this helpful article for resizing images before uploading them to the server. I want to use it for some repetitive HTML input but I'm having a problem altering the javascript code since I'm not really good in javascript.
This is what I've tried so far. But as can see, I didn't get the value for that imagefiles
function fileChange(e) {
for (var i = 1; i <= e.target.files.length; i++) {
document.getElementsByClassName('inp_img[i]').value = '';
var file = e.target.files[i-1];
alert(file);
if (file.type == "image/jpeg" || file.type == "image/png") {
var reader = new FileReader();
reader.onload = function(readerEvent) {
var image = new Image();
image.onload = function(imageEvent) {
var max_size = 800;
var w = image.width;
var h = image.height;
if (w > h) { if (w > max_size) { h*=max_size/w; w=max_size; }
} else { if (h > max_size) { w*=max_size/h; h=max_size; } }
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
canvas.getContext('2d').drawImage(image, 0, 0, w, h);
if (file.type == "image/jpeg") {
var dataURL = canvas.toDataURL("image/jpeg", 1.0);
} else {
var dataURL = canvas.toDataURL("image/png");
}
document.getElementsByClassName('inp_img[i]').value += dataURL + '|';
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
} else {
document.getElementsByClassName('inp_files[i]').value = '';
alert('Please only select images in JPG- or PNG-format.');
return false;
}
}
}
var imagefiles = document.getElementsByClassName('inp_files');
console.log(imagefiles);
for (var i=0; i<imagefiles.length; i++)
{
alert(imagefiles[i].value);
imagefiles[i].addEventListener('change',fileChange, false);
}
while ($row = mysql_fetch_array($result))
{ ?>
<div class="w3-quarter">
<div class="w3-card w3-container" style="min-height:150px">
<header class="w3-container w3-blue w3-row-padding w3-center w3-margin-top">
<label><b>Instruction <?php echo $counter; ?></b></label>
</header><br>
<b><?php echo $row['cf_941']; ?></b><br>
<?php echo $row['productname']." (".number_format($row['cf_949'])."%) - ".$row['cf_953']." ".$row['cf_955']; ?><br>
<?php echo "Area: ".$row['cf_951']." sm ";?>
<hr>
<label><b>Remarks</b></label><br>
<?php echo $row['cf_945']; ?><br>
<hr>
<b>Attached Photo</b><br>
<input class="inp_files[<?php echo $counter; ?>]" type="file">
<!--<?php echo $row['instructionsid']?> -->
<input class="inp_img[<?php echo $counter; ?>]" name="img[<?php echo $row['instructionsid']?>]" type="hidden" value="">
<p><strong>Note:</strong> Only .jpg, .jpeg,png formats allowed <br><hr>
<input class="w3-check" type="checkbox" name="itemStatus[<?php echo $row['instructionsid']?>]"
<?php if ($row['cf_947']=='1') {
echo "checked";
} ?> >
<label> Work completed</label><br><br>
</div>
</div>
<?php
$counter++;
}
?>
How can I alter this code to be able to resize the images from multiple input file and then send to PHP side?
That's because you are mixing the name and class attributes when you create your HTML code. Instead of:
<input class="inp_files[<?php echo $counter; ?>]" type="file">
it should read ...
<input class="inp_files" name="inp_files[<?php echo $counter; ?>]" type="file">
If you want to receive the proper instructionsid when you post the files back to the server, I would recommend to create a loop similar to this one:
<?php
while ($row = mysql_fetch_array($result)) {
?>
...
<input class="inp_files" id="<?php echo $row['instructionsid']?>" name="inp_files[<?php echo $row['instructionsid']?>]" type="file">
<input class="inp_img" name="inp_img[<?php echo $row['instructionsid']?>]" type="hidden" value="">
<input class="w3-check" name="itemStatus[<?php echo $row['instructionsid']?>]" type="checkbox" <?php print ($row['cf_947']=='1') ? 'checked' : ''?>>
...
<?php
}
?>
Your JS code will also need some rewrites as it contains several errors (i.e. document.getElementsByClassName('inp_img[i]').value = ''; searches for an element like <input class="inp_img[i]">, the i needs to be escaped properly).
function fileChange(e) {
for (let i = 0; i < e.target.files.length; i++) {
let self= this;
self.field= e.target.id;
let file = e.target.files[i];
console.log(self.field, file);
if (file.type == "image/jpeg" || file.type == "image/png") {
let reader = new FileReader();
reader.onload = function(readerEvent) {
let image = new Image();
image.onload = function(imageEvent) {
let max_size = 800;
let w = image.width;
let h = image.height;
if (w > h) { if (w > max_size) { h*=max_size/w; w=max_size; }
} else { if (h > max_size) { w*=max_size/h; h=max_size; } }
let canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
canvas.getContext('2d').drawImage(image, 0, 0, w, h);
let dataURL = '';
if (file.type == "image/jpeg") {
dataURL = canvas.toDataURL("image/jpeg", 1.0);
} else {
dataURL = canvas.toDataURL("image/png");
}
document.getElementsByName('inp_img[' + self.field + ']')[0].value += dataURL + '|';
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(file);
} else {
alert('Please only select images in JPG- or PNG-format.');
return false;
}
}
}
var imagefiles = document.getElementsByClassName('inp_files');
console.log(imagefiles);
for (var i=0; i<imagefiles.length; i++)
{
imagefiles[i].addEventListener('change',fileChange, false);
}
Basically i have to upload file by chunks as the file is very big,i tried using this solution uploading a file in chunks using html5 but the file is corrupt because the file reconstructed is not in order.
I tried to implement the answer given in the link but i really confused how can i implement it on my php page and my html page. If you guys could give me an advice or a way of doing it, that would be great. Thank you for your time.
The code :
upload.php
<?php
$target_path = "/home/imagesdcard/www/";
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];
$target_file = $target_path . basename($name);
$complete = "test.txt";
$com = fopen("/home/imagesdcard/www/".$complete, "ab");
error_log($target_path);
// Open temp file
$out = fopen($target_file, "wb");
if ( $out ) {
// Read binary input stream and append it to temp file
$in = fopen($tmp_name, "rb");
if ( $in ) {
while ( $buff = fread( $in, 1024) ) {
fwrite($out, $buff);
fwrite($com, $buff);
}
}
fclose($in);
fclose($out);
}
fclose($com);
?>
html
<!DOCTYPE html>
<html>
<head>
<title>Upload Files using XMLHttpRequest</title>
<script type="text/javascript">
window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
function sendRequest() {
var blob = document.getElementById('fileToUpload').files[0];
const BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
const SIZE = blob.size;
var i=0;
var start = 0;
var end = BYTES_PER_CHUNK;
while( start < SIZE ) {
var chunk = blob.slice(start, end);
uploadFile(chunk,i);
i++;
start = end;
end = start + BYTES_PER_CHUNK;
}
}
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}
function uploadFile(blobFile,part) {
//var file = document.getElementById('fileToUpload').files[0];
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "upload.php?num="+part);
xhr.onload = function(e) {
alert("loaded!");
};
xhr.send(fd);
//alert("oen over");
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
//alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
<input type="button" value="cancel" onClick="uploadCanceled();"/>
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button" onclick="sendRequest();" value="Upload" />
</div>
<div id="progressNumber"></div>
</form>
</body>
</html>
Your script doesn't work because js is async.
You should change your code to:
xhr.open("POST", "upload.php?num="+part, false);
and file save fine.
My solution for upload big files by chunk.
upload.php (php part)
<?php
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$chunk = $_FILES["chunk"]["tmp_name"];
$filename = $_POST['filename'];
if(!isset($_SESSION[$filename]))
{
$_SESSION[$filename] = tempnam(sys_get_temp_dir(), 'upl');
}
$tmpfile = $_SESSION[$filename];
if(isset($chunk))
{
file_put_contents($tmpfile, file_get_contents($chunk), FILE_APPEND);
}
else
{
rename($tmpfile, $filename);
}
exit();
}
?>
upload.php (html\js part)
<!DOCTYPE html>
<html>
<head>
<title>Upload Files using XMLHttpRequest</title>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript">
function sendRequest() {
// 1MB chunk sizes.
var chunk_size = 1048570;
var file = document.getElementById('file').files[0];
var filesize = file.size;
var filename = file.name;
var pos = 0;
while(pos < filesize) {
let chunk = file.slice(pos, pos+chunk_size);
pos += chunk_size;
var data = new FormData();
data.append('chunk', chunk);
data.append('filename', filename);
$.ajax({url:'upload.php',type: 'post',async:false,data: data,processData: false,contentType: false});
let percentComplete = Math.round(pos * 100 / filesize);
document.getElementById('progressNumber').innerHTML = (percentComplete > 100 ? 100 : percentComplete) + '%';
}
$.post('upload.php',{filename:filename});
}
</script>
</head>
<body>
<form>
<div class="row">
<label for="file">Select a File to Upload</label><br />
<input type="file" name="file" id="file" onchange="sendRequest();"/>
</div>
<div id="progressNumber"></div>
</form>
</body>
</html>
but this code have one bug - progress bar don't work in chrome because sync request used, work only in firefox.
I am creating a file upload script.
What I wanted to do is to upload the file without refreshing the page
Here's my code:
upload.php
<?php
function upload(){
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
<input type="file" name="file1[]" id="file1" multiple>
<input type="button" value="Upload File" onclick ="document.write('<?php upload(); ?>'')">
</form>
</body>
</html>
I wanted to do this on AJAX, I already searched for some examples but I want this to be simpler as possible.
By the way, is it possible for this to run without using any plugins or libraries?
I managed to find a solution for this. I separated the php script from the html and add a javascript file. I used ajax to call the PHP file to upload the files.
Here's my code;
index.php
<html>
<head>
<style type="text/css">
.upload{
width:500px;
background:#f0f0f0;
border: 1px solid #ddd;
padding: 20px;
}
.upload fieldset{
border: 0;
padding: 0;
margin-bottom:10px;
}
.uploads a, .uploads span{
display: block;
}
.bar{
width: 100%;
background: #eee;
padding: 3px;
margin-bottom:10px;
box-shadow: inset 0 1px 3px rgba(0,0,0,2);
border-radius: 3px;
box-sizing:border-box;
}
.barfill{
height: 20px;
display: block;
background: #ff6f01;
width:0px;
border-radius: 3px;
transition:width 0.8s ease;
}
.barfilltext{
color:#fff;
padding: 3px;
}
</style>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload Files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="button" id="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
</div>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files:f,
progressBar:pb,
progressText:pt,
processor: 'upload.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'), anchor, span, x;
if (data.failed.length) {
failed.innerHTML = '<p>The following files failed to upload</p>'
}
uploads.innerText = '' ;
for(x=0; x<data.succeeded.length; x = x+1){
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
anchor.target = '_blank';
succeeded.appendChild(anchor);
}
for(x=0;x<data.failed.length; x=x+1){
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
uploads.appendChild(failed);
},
error: function (){
console.log("Error");
}
});
});
</script>
</form>
</body>
</html>
upload.php
<?php
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() .'.'.$ext;
if (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded [] = array('name' => $name, 'file' => $file);
# code...
}else{
$failed[] = array('name' => $name );
}
}else{
echo "Error";
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' =>$failed
));
}
?>
upload.js
var app = app || {};
(function (obj) {
"use stricts;"
//Private Methods
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
if (typeof obj.options.finished === 'function') {
obj.options.finished(uploaded);
}
}else{
if (typeof obj.options.error === 'function') {
obj.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress',function(){
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', obj.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i=0; i<source.length; i = i+1){
data.append('file[]',source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function (value){
if (obj.options.progressBar !== undefined) {
obj.options.progressBar.style.width = value ? value + '%': 0;
}
if (obj.options.progressText !== undefined) {
obj.options.progressText.innerText = value ? value + '%' : 0;
}
};
obj.uploader = function(options){
obj.options = options;
if (obj.options.files !== undefined) {
ajax(getFormData(obj.options.files.files));
}
}
}(app));
anyways, thanks for the help guys. those were gladly appreciated.
Thanks!
I think in your case the simplest way is to put it into an iframe. I assume you have all code in one PHP file which is called upload.php. You would get something like this:
<?php
//Check if the action is upload file. If it is start upload
if(isset($_GET['action']) && $_GET['action'] == 'uploadFile')
{
if(!empty($_FILES['file1']['name'][0])){
$files = $_FILES['file1'];
$uploaded = array();
$failed = array();
$allowed = array('jpg','txt','png');
foreach ($files ['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if (in_array($file_ext,$allowed)) {
if ($file_error === 0) {
if($file_size<=20971520){
$file_name_new = uniqid('',true).'.'.$file_ext;
$file_destination = 'test_uploads/'.$file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
}else{
$failed[$position] = '[{$file_name}] failed to upload!';
}
}else{
$failed[$position] = '[{$file_name}] file is too large!';
}
}else {
$failed[$position] = '[{$file_name}] file extension is not allowed!';
}
}else{
$failed[$position] = '[{$file_name}] file extension not allowed!';
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
}
exit;
}
//Check if the action is getForm. If it is then display the form. This is to display the form in the iframe
elseif(isset($_GET['action']) && $_GET['action'] == 'getForm')
{
echo '
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php?action=uploadFile">
<input type="file" name="file1[]" id="file1" multiple>
<input type="submit" value="Upload File">
</form>';
exit;
}
?>
<html>
<head>
</head>
<body>
<h2>Multiple File Upload </h2>
<!-- IFrame which loads the form !-->
<iframe id="uploadFileFrame" style="width:100%; height:auto; border:0px;" src="upload.php?action=getForm"></frame>
</body>
</html>
Showing uploaded image after successful upload
you just go through with this code I have already given the answer of this type of question
I have a PHP program that takes in a image name and loads the image and displays the name and the image on the page.
The variable in javascrip is written as
var latest_image_name = '<?=$post_img_name?>';
The PHP code is
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
the html output, is being rendered as
<div id="image_list_wrapper">
<label class="lbl_image_name"><?=$file_name?></label>
</div>
And as you can see it seems that PHP has not replaced the tag with the posted image name.
The code works on the original server that it was developed on, it does not work when i migrated it to another server, i have tried two other servers both Centos 6.4 with apache and PHP installed. I am not sure what the setup was for the original server that it as does work on.
the full code is seen below
<?php
header('Refresh: 5; URL=display.php');
print_r($_POST['post_img_name']);
$target_directory = "uploaded_images";
if(!file_exists($target_directory)){
mkdir($target_directory);
}
if(isset($_POST['del_image'])) {
$del_image_name = $_POST['del_img_name'];
if(file_exists($target_directory."/".$del_image_name.".jpg")){
unlink($target_directory."/".$del_image_name.".jpg");
}
if(is_dir_empty($target_directory)){
die("Last image delete. No images exist now.");
}
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}else if(isset($_POST['post_img_name'])){
$post_img_name=$_POST['post_img_name'];
$post_img_temp_name = $_FILES['post_img_file']['tmp_name'];
}else{
$post_img_name = basename(get_latest_file_name($target_directory), '.jpg');
}
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$files_assoc_array = array();
$already_exists = "false";
if($total_number_of_files != 0){
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if ($filename==$post_img_name) {
$already_exists = "true";
}
}
}
if(!isset($_POST['del_image']) && isset($_POST['post_img_name'])){
$target_file = "$target_directory"."/".$post_img_name.".jpg";
$source_file = $post_img_temp_name;
if($already_exists == "true"){
unlink($target_file);
}
move_uploaded_file($source_file, $target_file);
}
foreach ($files_array as $file_info){
$info = pathinfo( $file_info->getFilename() );
$filename = $info['filename'];
if(!$file_info->isDot()){
$files_assoc_array[$filename] = $target_directory."/".$file_info->getFilename();
}
}
$files_assoc_array_keys = array_keys($files_assoc_array);
function get_latest_file_name($target_directory){
$files_array = new DirectoryIterator($target_directory);
$total_number_of_files = iterator_count($files_array) - 2;
$timestamps_array = array();
if($total_number_of_files!=0){
foreach($files_array as $file){
if(!$file->isDot()){
$timestamps_array[filemtime($target_directory."/".$file)] = $file->getFilename();
}
}
}
$max_timestamp = max(array_keys($timestamps_array));
return $timestamps_array[$max_timestamp];
}
function is_dir_empty($dir) {
if (!is_readable($dir))
return NULL;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
var files_array_text = '<?php echo implode(", ", $files_assoc_array)?>';
var files_array_keys_text = '<?php echo implode(", ", $files_assoc_array_keys)?>';
var files_array = files_array_text.split(", ");
var files_array_keys = files_array_keys_text.split(", ");
var files_assoc_array = createAssociativeArray(files_array_keys, files_array);
var latest_image_name = '<?=$post_img_name?>';
display_image(latest_image_name);
$('.lbl_image_name').click(function(){
$('#img_loading').show();
$('#img_display').hide();
var image_name = $(this).text();
$('.active').removeClass('active');
$(this).addClass('active');
display_image(image_name);
});
function createAssociativeArray(arr1, arr2) {
var arr = {};
for(var i = 0, ii = arr1.length; i<ii; i++) {
arr[arr1[i]] = arr2[i];
}
return arr;
}
function display_image(image_name){
var image_path = files_assoc_array[image_name];
$('#img_display').attr('src', image_path);
$('#img_display').load(image_path, function(){
$('#img_loading').hide();
$('#img_display').show();
})
}
});
</script>
</head>
<body>
<div id="container">
<div id="image_list_wrapper">
<?php
foreach($files_assoc_array_keys as $file_name){
if($file_name==$post_img_name){
?>
<label class="lbl_image_name active"><?=$file_name?></label>
<?php
}else{
?>
<label class="lbl_image_name"><?=$file_name?></label>
<?php
}
}
?>
</div>
<div class="separator"></div>
<div id="image_display_wrapper">
<div id="img_loading_wrapper">
<img src="images/loading.gif" id="img_loading"/>
</div>
<img src="" id="img_display"/>
</div>
<div style="clear: both">
</div>
</div>
Go Back
</body>
</html>
As arbitter has pointed out my server did not support <?= ... ?> it worked after i changed to <?php print $variable_name ?>