get width of uploaded image (before uploading file to server) - javascript

I have some code that i changed. It was prevusly to get file ext. I wannted it to get width of uploded image( before even clicking submit input ) and if it's too small giving alert. Problem is that i dont really know how i can connect this js code with html form.
<form id="add" method="POST" enctype="multipart/form-data" action="upload.php">
<input type="file" id= "filput" style="margin-bottom:30px; margin-top:20px;" name="file" size="40" />
</form>
$("#filput").on('change', function () {
var w = $(this).width();
if (w < 500) {
alert("too small");
} else {
alert("big");
}
});

The this referrs to the input not the image. You have too use the HTML5 file API.
You can use this example: How to get the image width from html 5 file API
Code example: copied from: Getting Image Dimensions using Javascript File API
$("#filput").on('change', function () {
var fr = new FileReader;
fr.onload = function() { // file is loaded
var img = new Image;
img.onload = function() {
alert(img.width); // image is loaded; sizes are available
};
img.src = fr.result; // is the data URL because called with readAsDataURL
};
fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating
});

Related

upload and preview file before uploading replacing last image issue

I am trying to upload image and previewing it one by one but it replace last image.
I want to keep adding up more and more images but only last image is showing in received $_FILES array
Keep all upload images in form and keep them previewing.
my code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" id="add-gallary" name="filecollections[]">
<input type="submit" value="Submit">
<div class="gallery"></div>
</form>
<script>
$(function() {
var upload_count = 0;
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
// input.files.append(input.files[i]);
reader.readAsDataURL(input.files[i]);
upload_count++;
}
}
};
$('#add-gallary').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
</script>
The reason why only last images is getting uploaded is that you are storing the images in an array because you have single file upload input.
If you want upload multiple images you have previewer on form submit you would need to store them in array i have named imagesToUpload
Once you have all the images previwed and ready to submit the form with images you have selected and previewed you have loop forEach through that array imagesToUpload and append those file data to formData.
You will then this formData to your backend and upload all the images on backend using ajax request.
Run snippet below to see that array is using .push function to store all your images you have previewed.
$(function() {
var upload_count = 0;
//Store images in array
var imagesToUpload = []
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
// input.files.append(input.files[i]);
//Push images to array on preview
imagesToUpload.push(input.files[i])
reader.readAsDataURL(input.files[i]);
upload_count++;
}
}
};
$('#add-gallary').on('change', function() {
imagesPreview(this, 'div.gallery');
console.log(imagesToUpload)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" id="add-gallary" name="filecollections[]">
<input type="submit" value="Submit">
<div class="gallery"></div>
</form>

Display image from a given url

I have an array with 3 cells.At the first cell i have a textarea where you can insert the url of an image.At the second cell i have a button which when you click the image display at the third cell where i have a div to display the image.The question is how can i display the image either from the internet either from local?
The code i wrote is:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
mydiv.innerHTML = url.value;
}
<html>
<body>
<input type="text" id="imagename" value="" />
<input type="button" id="btn" value="GO" />
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
img = document.createElement('img');
img.src = document.getElementById('imagename').value;
document.body.appendChild(img);
}
</script>
</body>
</html>
You can see the sample code will add the images from an array to the document.
You could also append the images to any of the elements in your function by using url.appendChild
var arr = ['http://via.placeholder.com/350x150', 'http://via.placeholder.com/350x250','http://via.placeholder.com/350x350']; // hold image urls in an array.
arr.forEach(function(item){
// loop through array and add images to the document.
var img = new Image();
img.src = item;
document.body.appendChild(img);
});
In order to do both you would need to change your html and code.
For the case when the user has a url you can just create a new image and append it to your div setting the image's src to the url that was set in the input:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
var image = new Image;
mydiv.appendChild(image);
image.src = url.value;
}
Now to get it to display a local image you will need a file input or a drag and drop scheme as you cannot access local files without some type of user interaction.
So you would, for example, need to change your html to include a file input, and grab a reference to the selected file the user selects. Then use FileReader to read the file, and finally display it
HTML
<input type="file" id="imagefile">
JS
//input reference
var imageinput = document.getElementById("imagefile");
imageinput.addEventListener('change',function (){
var mydiv = document.getElementById("idofdivtodisplayimg");
var image = new Image;
mydiv.appendChild(image);
//FileReader instance
var reader = new FileReader;
reader.addEventListener('load',function(){
//reader.result will contain a dataURL that can be used
//like a regular image url
image.src = reader.result;
});
//read the file as a dataURL
reader.readAsDataURL( imageinput.files[0] );
});
This does both, it let's you upload an image (or at least load it to the browser) or give a URL to an image source. Click the button and the image is loaded and displayed!
This snippet uses the FileReader API to get the uploaded image and display it in an image element
function uploadOrNot() {
if (document.querySelector("input[type=file]").files[0]){
let input = document.querySelector("input[type=file]");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
display(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
} else if (document.querySelector("input[type=text]").value){
display(document.querySelector("input[type=text]").value);
}
}
function display(res) {
let img = document.createElement("IMG");
img.src=res;
document.querySelector("#result").appendChild(img);
}
<div id="urlOrUpload">
<input type="text"/>
<br>
<input type="file" accetp="image/*"/>
</div>
<div id="buttonHolder">
<button type="button" onclick="uploadOrNot()">Display</button>
</div>
<div id="result"></div>
I partly solved it by replacing the div at the third cell with an img tag and at the function i wrote above, i chenged it to:
var image = document.getElementbyId("imageid");
var url = document.getElementbyId("urlid");
image.src = url.value;
But at the table i have,i also have a button where you can add a same row as above.How can i do this function for every url that is placed at every textbox?

Pass image from one .jsp to another .jsp

I am learning JSP and I can't find an answer to the following question:
I want to upload the image file in one page, pass it to another and show it there like (based on this question):
first.jsp
<form method="post" onsubmit="save()" action="second.jsp" enctype="multipart/form-data">
<input type="file" name="openFile" onchange="reloadPreview()">
<canvas name="preview"></canvas>
<input type="submit" value="Save"/>
</form>
<script>
function reloadPreview(){
var preview = document.getElementsByName("preview")[0];
var file = document.getElementsByName("openFile")[0].files[0];
var reader = new FileReader();
var picture = new Image;
reader.onloadend = function () {
picture.src = reader.result;
preview.width = picture.width;
preview.height = picture.height;
var context = preview.getContext("2d");
context.drawImage(picture, 0, 0);
dataUrl = preview.toDataURL();
};
if (file) {
reader.readAsDataURL(file);
}
}
function save() {
window.location = "second.jsp?imgUrl="+dataUrl;
document.getElementById("form").submit();
}
var dataUrl;
</script>
1) What should I do to access canvas content from second.jsp?
2) Can I access openFile file without uploading it to canvas (for example if file is not an image)?
Source:
<%session.setAttribute("Down1","download.png");%>
<td>Image: </td>
<td><img src="download.png" width="516" height="516" alt="Down" name="Down1"/></td>
Destination:
<td><img src="download.png" width="516" height="516" alt="Down" name="Down1"/></td>

Preview image HTML & JavaScript

I am working on an image uploader and I am currently trying to build up an image preview before the upload is done. I have this HTML code:
<input type="file" id="id_imatgeNewPeces"></input><br></br>
<img id="previewing" src="" />
Then I add a listener to the input like this:
document.getElementById('id_imatgeNewPeces').addEventListener('change', this.handleFileSelect, false);
And finally the function handleFileSelect:
handleFileSelect: function(oEvent) {
var file = oEvent.target.files[0];
if (!file.type.match('image.*')) {
sap.m.MessageToast.show("El archivo seleccionado no es una Imagen");
} else {
var readerURL = new FileReader();
readerURL.onload = function() {
$('#previewing').attr('src', readerURL.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
return true;
};
readerURL.readAsDataURL(file);
}
},
I don't know why when I select a file which is not an image it displays the message but when I do select an image when the method onload ends no image is displayed and in addition it seems that the listener has been lost because no further calls are done when if I select another image.
The funny thing is that if I place a breakpoint on line '$('#previewing').attr('height', '230px');' I can see the image but when I continue it disappears. In addition when the method onload ends the fileinput "resets" I mean that it says that it has no selected files.
Besides being a old question, I've found that your code is working as expected:
I just don't undestand why use a native addEventListener() when you are using jquery for DOM manipulation, being easily replaced by:
$("#id_imatgeNewPeces").change(handleFileSelect);
var handleFileSelect = function(oEvent) {
var file = oEvent.target.files[0];
if (!file.type.match('image.*')) {
console.log("El archivo seleccionado no es una Imagen");
} else {
var readerURL = new FileReader();
readerURL.onload = function() {
$('#previewing').attr('src', readerURL.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
return true;
};
readerURL.readAsDataURL(file);
}
};
$("#id_imatgeNewPeces").change(handleFileSelect);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="id_imatgeNewPeces">
<br/><br/>
<img id="previewing" src="" />

Javascript Image Preview for page with lots of forms

I have a bunch of forms on a page that allow a user to edit information for each respective form. One of the inputs for the form is an image upload.
The forms are of the form below:
<form class="myForm" ...>
<div class="imagePreview"></div>
<input type="file" name="myImage" onchange="handleFiles(this.files)" />
</form>
And I have javascript to handle the image preview as follows:
function handleFiles(files) {
$(".obj").remove();
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var pic_div = document.getElementById("imagePreview");
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
pic_div.appendChild(img);
var reader = new FileReader();
reader.onload = (
function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
}
)(img);
reader.readAsDataURL(file);
}
}
I want to replace the line:
var pic_div = document.getElementById("imagePreview");
with the appropriate line. This is where I am getting confused. I don't know how to refer to the div of class "imagePreview" for THIS FORM of class myForm.
Any help is much appreciated.
The problem is that you're getting the div with the Id imagePreview, when the div in the form have the imagePreview CSS class, what you can do is either give the div the required id, more less like this:
<div id="imagePreview"></div>
Or, if you will have multiple divs with the same class get them using jQuery like this:
$(".imagePreview").each(function(index){
//Do Something
});
Or:
var pic_div = $(".imagePreview")[0]

Categories

Resources