JQuery File Input - Read image width & height - javascript

I'm trying to read (input type="file") image file's original width / height. My code gives me "undefined". I suppose because i'm not loading image to server or anywhere.
Here is my code;
<script>
$( document ).ready(function() {
$('#texture_modal').click(function () {
var texture_name = $('#texture_name').val();
var thumb_img = $('#thumb_img').val().replace(/^.*\\/, "");
var big_img = $('#big_img').val().replace(/^.*\\/, "");
var real_img = $('#real_img').val().replace(/^.*\\/, "");
var img_size = document.getElementById("real_img").files[0].size / (1024*1024); // Get real_img size in MB
var texture_size = img_size.toFixed(2); // get rid of decimals in real_img size MB
var texture_category = $('#texture_category').val();
var texture_description = $('#texture_description').val();
// THIS IS THE STUFF WHICH I WANT TO GET IMAGE WIDTH
var texture_dim = document.getElementById("real_img").naturalWidth;
console.log(texture_dim);
}); //End click function
}); //End document ready
</script>
And here is my input fields. I have multiple file inputs, whichs are for thumbnail image, big image and real image. I need real image width only, others will be upload to server. Here is my input fields;
<!-- this fields are inside a bootstrap modal -->
<div class="modal-body">
<div class="input-group input-group-sm">
<div class="input-group-prepend">
<span class="input-group-text"><small>Texture Name</small></span>
</div>
<input type="text" class="form-control" id="texture_name">
</div>
<div class="form-group pt-1">
<small>Thumbnail Img(200*200)</small>
<input type="file" class="form-control form-control-sm" id="thumb_img">
<small>Big Img(445*445)</small>
<input type="file" class="form-control form-control-sm" id="big_img">
<!-- this one i want to take width without post or upload anywhere -->
<small>Real Img</small>
<input type="file" class="form-control form-control-sm" id="real_img">
<!-- taking categories with php function -->
<small>Category</small>
<select id="texture_category" class="form-control form-control-sm">
<option selected disabled>----- Choose a Category -----</option>
<?php foreach($texture_categories as $key){?>
<option><?php echo $key; ?></option>
<?php } ?>
</select>
<small>Description :</small>
<textarea id="texture_description" class="form-control form-control-sm"></textarea>
</div>
</div>

can you try to assign an Image and get it
var fileUpload=document.getElementById("photoInput");
function Test(){
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var width = this.naturalWidth || this.width;
var height = this.naturalHeight || this.height;
console.log(height,width)
}
};
}
<div class="photo">
<input type="file" name="photo" id="photoInput" onchange="Test(this)"/>
</div>
in your example
$( document ).ready(function() {
$(".modal").modal()
});
function Test(){
var fileUpload=document.getElementById("thumb_img");
var reader = new FileReader();
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
var image = new Image();
image.src = e.target.result;
image.onload = function () {
var width = this.naturalWidth || this.width;
var height = this.naturalHeight || this.height;
console.log(height,width)
}
};
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-- this fields are inside a bootstrap modal -->
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="input-group input-group-sm">
<div class="input-group-prepend">
<span class="input-group-text"><small>Texture Name</small></span>
</div>
<input type="text" class="form-control" id="texture_name">
</div>
<div class="form-group pt-1">
<small>Thumbnail Img(200*200)</small>
<input type="file" class="form-control form-control-sm"onchange="Test(this)" id="thumb_img">
<small>Big Img(445*445)</small>
<input type="file" class="form-control form-control-sm" id="big_img">
<!-- this one i want to take width without post or upload anywhere -->
<small>Real Img</small>
<input type="file" class="form-control form-control-sm" id="real_img">
<!-- taking categories with php function -->
<small>Category</small>
<select id="texture_category" class="form-control form-control-sm">
<option selected disabled>----- Choose a Category -----</option>
<?php foreach($texture_categories as $key){?>
<option><?php echo $key; ?></option>
<?php } ?>
</select>
<small>Description :</small>
<textarea id="texture_description" class="form-control form-control-sm"></textarea>
</div>
</div>
</div>
</div>
</div>

Related

How to preview image when upload to multiple forms

I have 2 image upload forms, when one is uploaded it should show a preview of the uploaded image. However, when I upload an image in one of the input forms, both forms display a preview of the last uploaded image. How do I make the preview only appear on the uploaded form?
Here's my code :
<div class="container">
<form action="save.php" method="post" enctype="multipart/form-data">
<!-- rows -->
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview1" class="img-thumbnail1">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img1" class="file1" id="file1">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image1" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<img src="images/80x80.png" id="preview2" class="img-thumbnail2">
<div class="form-group">
<div id="msg"></div>
<input type="file" name="img2" class="file2" id="file2">
<div class="input-group my-3">
<div class="input-group-append">
<button type="button" id="select_image2" class="browse btn btn-dark">select image</button>
</div>
</div>
</div>
</div>
</div>
<button type="submit" name="btn_save" class="btn btn-success">Save</button>
</form>
</div>
<script>
$(document).on("click", "#select_image1", function() {
var file = $(this).parents().find(".file1");
file.trigger("click");
});
$('input[type="file"]').change(function(e) {
var fileName1 = e.target.files[0].name;
$("#file1").val(fileName1);
var reader = new FileReader();
reader.onload = function(e) {
// get loaded data and render thumbnail.
document.getElementById("preview1").src = e.target.result;
};
// read the image file as a data URL.
reader.readAsDataURL(e.target.files[0]);
});
// 2
$(document).on("click", "#select_image2", function() {
var file2 = $(this).parents().find(".file2");
file2.trigger("click");
});
$('input[type="file"]').change(function(el) {
var fileName2 = el.target.files[0].name;
$("#file2").val(fileName2);
var reader2 = new FileReader();
reader2.onload = function(el) {
// get loaded data and render thumbnail.
document.getElementById("preview2").src = el.target.result;
};
// read the image file as a data URL.
reader2.readAsDataURL(el.target.files[0]);
});
</script>
I've tried changing the script code, but it doesn't work. Please help. Thank you.

Uploaded image is not returned to PHP

I am trying to make a form for editing a product but if I upload a image the image can not be found by my PHP code it throws this error:
Notice: Undefined index: image in C:\xampp\htdocs\pages\shopmanager\admin\producteditor.php on line 10
Notice: Undefined index: image in
C:\xampp\htdocs\pages\shopmanager\admin\producteditor.php on line 11
Upload failed
This is my Code:
$db = new Database;
$product = mysqli_fetch_array($db->db_query("SELECT * FROM product WHERE ID = '" . $_GET['id'] . "'"));
$image = mysqli_fetch_array($db->db_query("SELECT name,src FROM images WHERE id =".$product['image-id']));
$category = $db->db_query("SELECT * FROM category");
$productcat = mysqli_fetch_array($db->db_query("SELECT `cat-id` FROM `category-product` WHERE `prod-id` = ".$product['ID']));
if(isset($_POST['submit'])){
$uploaddir = '/../../../src/images/';
$uploadfile = $uploaddir . basename($_FILES['image']['name']);
if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
}
?>
<!--page content-->
<div class="col-9">
<div style="background-color:#c6c8ca !important; color:black" class="jumbotron">
<div class="container">
<form class="well form-horizontal" action="producteditor.php?id=<?= $_GET['id'] ?>" method="post"
id="producteditor_form">
<fieldset>
<!-- Upload image input-->
<input id="upload" name="image" type="file" onchange="readURL(this);"
class="form-control border-0" accept="image/*" hidden>
<div class="input-group-append">
<label for="upload" class="btn btn-light m-0 rounded-pill px-4"> <i
class="fa fa-cloud-upload mr-2 text-muted"></i><small
class="text-uppercase font-weight-bold text-muted"> Kies
bestand</small></label>
</div>
<!-- Uploaded image area-->
<div class="image-area mt-4"><img id="imageResult"
src="../../../<?=$image['src']?>" alt="<?=$image['name']?>"
class="img-fluid rounded shadow-sm mx-auto d-block">
</div>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<div class="text-center">
<button class="btn btn-lg btn-success form-spacing-top"
name="submit">Opslaan</button>
</div>
</div>
</fieldset>
</form>
</div>
</div><!-- /.container -->
</div>
</div>
<div class="col"></div>
</div>
</div>
<script>
/* ==========================================
SHOW UPLOADED IMAGE
* ========================================== */
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imageResult')
.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$(function() {
$('#upload').on('change', function() {
readURL(input);
fetch(url, {
method: 'POST',
body: readURL(input)
});
});
});
/* ==========================================
SHOW UPLOADED IMAGE NAME
* ========================================== */
var input = document.getElementById('upload');
var infoArea = document.getElementById('upload-label');
input.addEventListener('change', showFileName);
function showFileName(event) {
var input = event.srcElement;
var fileName = input.files[0].name;
infoArea.textContent = 'File name: ' + fileName;
}
</script>
Your <form> needs to have the enctype='multipart/form-data' attribute.
See: What does enctype='multipart/form-data' mean?

How to Upload image with some field?

I am trying to upload image with some required field like name, description. When i am inserting data without the image field it works, but when trying to upload the image file as well its not inserting data to database. Could anyone tell me what may be wrong with my code?
Controller
public function store(Request $request)
{
$this->validate($request, [
'cat_name' => 'required|max:255',
'description' => 'required|min:6',
'cat_pic' => 'required|image|mimes:jpg,jpeg,png',
]);
$fileName = null;
if ($request()->hasFile('cat_pic')) {
$file = $request()->file('cat_pic');
$fileName = time().'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('/uploads/products/cats/');
$file->move($destinationPath, $fileName);
$this->save();
}
Catagories::create([
'cat_name' => $request->input('cat_name'),
'description' => $request->input('description'),
'cat_pic' => $fileName,
]);
Session::flash('alert', __('messages.created'));
Session::flash('alertClass', 'success');
return redirect()->route('catagories');
}
View
<div class="col-md-4 offset-5">
<div class="form-group">
<form role="form" action="<?php echo e('/products/cats') ?>" method="POST" id="createcat" >
{{ csrf_field() }}
<p>
Create New Product Category
</p>
<div class="form-group">
<label for="cat_name">
Name*:</label>
<input type="text" class="form-control"
id="cat_name" name="cat_name" required maxlength="50">
</div>
<div class="form-group">
<label for="cat_pic">Category Image* </label>
<input data-preview="#preview" class="form-control" name="cat_pic" type="file" id="cat_pic">
<img class="col-md-6" id="preview" height="100px" width="20px" src="">
</div>
<div class="form-group">
<label for="description">
Description*:</label>
<textarea class="form-control" type="textarea" name="description"
id="description" placeholder="Category Description"
maxlength="600" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-lg btn-success btn-block" id="btncreatecat">Create</button>
</form>
</div>
</div>
#endsection
#push('scripts')
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#cat_pic").change(function(){
readURL(this);
});
</script>
Route
Route::resource('products/cats', 'Admin\CatController');
and some JQuery to preview the image
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#cat_pic").change(function(){
readURL(this);
});
</script>
you need to add enctype="multipart/form-data" to the <form> tag.
Like this:
<form role="#" action="#" method="#" id="#" enctype="multipart/form-data">
So your form can send other things than text.
I realized the problem is I just forgot to add enctype="multipart/form-data" inside the form tag.

HTML required functions with javascript which required function doesnt work

Can anyone help me with this required function doesnt work. i am uploading a picture in my html/php web page and before i upload a picture i set a dropdown option which is to upload or not, and this is my code:
<script>
function papeles()
{
var x = document.getElementById('tagoan1').value;
if (x == "YES")
{
// alert('aaaa');
$('#imgInp').addClass("required");
$('#imgInp').removeClass("hidden");
$('#blah').removeClass("hidden");
} else
{
//alert('bbbbb');
$('#imgInp').addClass("hidden");
$('#imgInp').removeClass("required");
$('#blah').addClass("hidden");
}
}
</script>
<div class="col col-sm-5">
<label>Attachment </label>
<select class="form-control" id="tagoan1" name="taguan" onchange="papeles()" required disabled>
<option value="">With Attachment?</option>
<option value="YES">Yes</option>
<option value="NO">No</option>
</select>
</div>
<div class="row text-center">
<div class="col col-sm-6">
<div class="form-group" style="margin:0;">
<input type='file' name="image" id="imgInp" value="" class="hidden required btn btn-block btn-sm" style="padding-left:3em;width:300px"/>
</div>
<img id="blah" src="customer/tagoan/images/noimage.png" height="200px" width="300px" name="tae" border-color="white" placeholder="" class="hidden"/>
</div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script>
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]);
}
}
$("#imgInp").change(function () {
readURL(this);
});
</script>
The problem is that when i click yes but i dont choose a file, the picture will still submit it should not submit because of the add class required how to solve this.
when you hide an input, it is not removed from the page. So, the file input stays in the form, and sumbitted regardless if it's hidden or not. What you need is to remove the input from DOM:
if (x == "YES")
{
$('#imgInp').remove() // file input gone
$('#blah').removeClass("hidden");
} else
{
//you should add an ID to the parent of imgInp instead of referring as .form-group
$('.form-group').prepend("<input type='file' name='image' id='imgInp' value='' class='required btn btn-block btn-sm' style='padding-left:3em;width:300px'/>")
$('#blah').addClass("hidden");
}
is it okay if you just use .hide() and .show() of jQuery?

Cannot read property '0' of undefined input file in bootstrap module window

I am trying to create a form inside a Bootstrap modal. it should contain the input file field and preview a chosen image, so I can use Jcrop to crop the image.
So here is what am I doing now:
<script type="text/javascript">
$('#new-menu').on('shown.bs.modal', function (event) {
var modal = $(this);
var src = modal.find(".modal-body .upload");
var target = modal.find(".image");
src.bind("change", function () {
// fill fr with image data
modal.find(".jcrop-holder").remove();
readUrl(modal,target,src);
initJcrop(target);
});
});
function readUrl(modal,target,src){
if (src.files && src.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
target.attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
initJcrop(target, modal);
}
else alert(src.files[0]);
}
}
function showCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
function initJcrop(img) {
jcrop_api = $.Jcrop(img);
jQuery(img).Jcrop({
aspectRatio: 16 / 9,
onChange: showCoords,
setSelect: [0, 90, 160, 0],
onSelect: showCoords
}, function () {
modal.find(".jcrop-holder").css({
left: "50%",
marginLeft: -img.width / 2 + "px"
});
});
}
</script>
But i get this error
'Cannot read property '0' of undefined'
HTML
<form action="place/{id}/new/service/">
<div class="input-group">
<img src="http://placehold.it/160x90" class="image"/>
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon1">
<i class="glyphicon glyphicon-apple"></i>
</span>
<input type="text" id="form-name" class="form-control"
placeholder="Назва" value="" aria-describedby="basic-addon1"/>
</div>
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">
<i class="fa fa-tag"></i>
</span>
<input type="number" id="form-price" class="form-control"
placeholder="Ціна" value="" aria-describedby="basic-addon1"/>
<span style="padding:2px 5px" class="input-group-addon"><i>.грн</i></span>
</div>
<div class="input-group">
<textarea class="form-control place_description" style="resize: none" rows="5"
placeholder="Короткий опис послуги"></textarea>
</div>
<div style="text-align: center">
<small class="description-info">Залишилося 160 символів</small>
</div>
<div class="input-group">
<input type="file" class="upload"/>
</div>
<button id="new-service" class="btn btn-primary" type="submit">Зареєструвати</button>
</form>
The src you are passing in function readUrl(modal,target,src) is a jQuery element when you need is to access the DOM element. Have
src.get(0).files && src.get(0).files
Instead of
src.files && src.files[0]

Categories

Resources