Uploading image through PHP form - javascript

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?

Related

Local file upload -> Canvas greyscale and downscale -> ocr.space

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 ...
?>

Resize Image from Client-side for multiple HTML input

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);
}

uploading a file in chunks using html5 , javascript and PHP

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.

How to make mini images box with upload images button in html,js,php

I'm still learning to programme.
I want to make images box like this:
Button "+" is for upload images. How I can make this design with these functions?
I have some code but it uploads only one image.
My HTML code:
<div class="item-card">
<div class="card-section">
<div class="clearfix">
<!---<div class="pull-right">
<input type="file" name="fileToUpload" id="fileToUpload">
</div>---->
<hr />
<div class="pull-right">
<input class="upload_file" type="file" name="fileToUpload" id="fileToUpload" style="">
<div class="item-images clearfix">
<div class="empty-text">
Upload images
</div>
</div>
</div>
</div>
<hr />
</div>
</div>
Jquery(which show upload image):
$('#fileToUpload').on('change', function() {
var file = this.files[0];
var imagefile = file.type;
var imageTypes = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
if (imageTypes.indexOf(imagefile) == -1) {
//display error
return false;
$(this).empty();
}
else {
var reader = new FileReader();
reader.onload = function(e) {
$(".empty-text").html('<img src="' + e.target.result + '" />');
};
reader.readAsDataURL(this.files[0]);
}
});
And PHP code(which upload the images to database)
if($_FILES["fileToUpload"]["tmp_name"]) {
$uploadOk = 1;
//$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$uploadOk = 0;
}
// Allow certain file formats
/*if($imageFileType != "jpg") {
$uploadOk = 0;
}*/
// Check if $uploadOk is set to 1
if ($uploadOk == 1) {
$this->db->insert('products_images', array('product_id' => $product_id));
$insert = $this->db->insert_id();
$target_dir = "./" . p_image_path();
$target_file = $target_dir . '/' . $insert . '.jpg';
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$this->db->update("products", array('main_image' => $insert), array('id' => $product_id));
}
}
redirect(site_url('mystore/products/edit/' . $product_id));

How to preview images before upload with php,mysql [duplicate]

This question already has answers here:
Preview an image before it is uploaded
(29 answers)
Closed 3 years ago.
I'm a beginner and still learning to programme.
I want to do something like this:
https://ufile.io/z2w0l
My question is how to preview a few images before uploading in the database with php,mysql?
I have code but it work like this:
When I choose which image i want to upload, the image doesn't display. Image is displaying when i click on submit button. I will take the picture of my layout here: https://prnt.sc/mv1ef0 (this is my form where i can upload image), https://prnt.sc/mv1erl (this is my submit button "Post"). When i click on submit button the page is refreshing and the image is displaying(like this photo): https://prnt.sc/mv1fjg
I want to preview picture first: https://prnt.sc/mv1iiz (in this box)
Here is my php code:
public function create() {
$this->requireSession();
$this->load->model('store_model');
$visible = 0;
if($this->input->post('is_visible') == 'on') {
$visible = 1;
}
$promotion = 0;
if($this->input->post('is_promotion') == 'on') {
$promotion = 1;
}
$internal = 0;
if($this->input->post('is_internal') == 'on') {
$internal = 1;
}
$userId = $this->authorization->getUserId();
$storeId = $this->authorization->getStore();
$price = $this->input->post('price');
$prev_price = $this->input->post('prev_price');
if($promotion == 1) {
$price = $this->input->post('prev_price');
$prev_price = $this->input->post('price');
}
date_default_timezone_set('Europe/Sofia');
$data = array(
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
'price' => $price,
'currency' => 'BGN',
'is_promotion' => $promotion,
'promotion_price' => $prev_price,
'quantity' => $this->input->post('quantity'),
'status' => $this->input->post('status'),
'main_image' => 0,
'is_internal' => $internal,
'is_visible' => $visible,
'url_address' => $this->input->post('url'),
'total_views' => 0,
'total_likes' => 0,
'total_comments' => 0,
'product_added' => date("Y-m-d H:i:s"),
'is_active' => 1,
'category_id' => $this->input->post('category_id'),
'user_id' => $this->authorization->getUserId(),
'store_id' => $storeId,
'brand_id' => $this->input->post('brand_id')
);
$this->db->insert("products", $data);
$product_id = $this->db->insert_id();
$this->db->query("UPDATE categories SET total_products = total_products + 1 WHERE id = " . $this->input->post('category_id'));
$this->db->query("UPDATE stores SET total_products = total_products + 1 WHERE id = " . $storeId);
$this->db->query("UPDATE users SET total_products = total_products + 1 WHERE id = " . $userId);
$tags = $this->input->post('tags');
$this->load->model('tag_model');
$this->tag_model->updateTags($tags, $product_id);
$this->load->model('category_model');
$this->load->model('attribute_model');
$attributes = $this->category_model->getOnlyAttributes($this->input->post('category_id'));
$values = array();
foreach($attributes as $row) {
$values[] = array('product_id' => $product_id, 'attribute_value_id' => $this->input->post('attribute_id' . $row->attribute_id));
}
if($attributes) {
$this->attribute_model->updateProductAttributes($values, $product_id);
}
if($_FILES["fileToUpload"]["tmp_name"]) {
$uploadOk = 1;
//$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
$uploadOk = 0;
}
// Allow certain file formats
/*if($imageFileType != "jpg") {
$uploadOk = 0;
}*/
// Check if $uploadOk is set to 1
if ($uploadOk == 1) {
$this->db->insert('products_images', array('product_id' => $product_id));
$insert = $this->db->insert_id();
$target_dir = "./" . p_image_path();
$target_file = $target_dir . '/' . $insert . '.jpg';
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
$this->db->update("products", array('main_image' => $insert), array('id' => $product_id));
}
}
redirect(site_url('mystore/products/edit/' . $product_id));
}
Here is my HTML code:
<div class="item-card">
<div class="card-section">
<div class="clearfix">
<!---<div class="pull-right">
<input type="file" name="fileToUpload" id="fileToUpload">
</div>---->
<div class="pull-right">
<span class="btn btn-white upload_image" type="file" id="fileToUpload">Upload image</span>
<input class="upload_file" type="file" name="fileToUpload" id="fileToUpload" style="display:none;">
</div>
<h2 class="al">Images</h2>
</div>
<hr />
<div class="item-images clearfix">
<div class="empty-text">
Upload images
</div>
</div>
</div>
</div>
You need to use Jquery onchange event when the file is selected read the file using FileReader
$('#fileToUpload').on('change', function() {
var file = this.files[0];
var imagefile = file.type;
var imageTypes = ["image/jpeg", "image/png", "image/jpg", "image/gif"];
if (imageTypes.indexOf(imagefile) == -1) {
//display error
return false;
$(this).empty();
}
else {
var reader = new FileReader();
reader.onload = function(e) {
$(".empty-text").html('<img src="' + e.target.result + '" />');
};
reader.readAsDataURL(this.files[0]);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="upload_file" type="file" name="fileToUpload" id="fileToUpload">
<div class="item-images clearfix">
<div class="empty-text">
Upload images
</div>
</div>

Categories

Resources