I have a simple form which allows you to paste an image. The image is previewed using JavaScript.
In the snippet the paste area is a textarea for testing purposes.
After the image is pasted, it’s not yet in the form’s data. Is there a way of doing this so that the image can be uploaded on submit?
var previews = document.querySelector('div#previews');
var form = document.querySelector('form#data');
form.elements['stuff'].onpaste = function (event) {
files = event.clipboardData.files;
var img = document.createElement('img');
img.width = '200';
previews.appendChild(img);
var reader = new FileReader();
reader.onload = () => {
img.src = reader.result;
};
reader.readAsDataURL(files[0])
};
textarea, input, button {
display: block;
}
<form id="data">
<textarea name="stuff"></textarea>
<input type="file" name="photo">
<button name="doit">OK</button>
</form>
<div id="previews">
</div>
Related
I am looking for an example where the value of the <input type="file"> can be stored into a variable and then from there stored into localStorage so it is not lost when the page is refreshed, and I couldn't find the solution for what I was looking for.
function myFunction() {
//Get value of input type file
let userInput = document.getElementById("uploadImage").value;
//Store value into LocalStorage
localStorage.setItem("image", JSON.stringify(userInput))
}
// Display "image" in Local storage as src of img preview even after page refreshes
document.getElementById("imagePreview").setAttribute("src", JSON.parse(localStorage.getItem("image")))
img {
max-width: 300px;
}
<input type="file" accept="image/*" id="uploadImage">
<br>
<button onclick="myFunction()">
Submit Picture
</button>
<br>
<img id="imagePreview">
To summarize, I want to know how to save the input value into a variable, then the variable into the local storage. Finally, display the localStorage in an image tag so it is not lost when the page is refreshed. Please let me know if you have any questions as I know it might be a bit confusing. Here's a jsFiddle as shown here: https://jsfiddle.net/vedt_/zrvuwbj7/44/#&togetherjs=gbLynsQ627 feel free to edit it if you know how to do it.
You can convert the image into base64 and store it as follows:
function myFunction() {
const file = document.querySelector('#uploadImage').files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
localStorage.setItem("image", reader.result);
document.getElementById("imagePreview").setAttribute("src", localStorage.getItem("image"))
};
}
if(localStorage.getItem("image"))
document.getElementById("imagePreview").setAttribute("src", localStorage.getItem("image"))
img {
max-width: 300px;
}
<input type="file" accept="image/*" id="uploadImage"><br>
<button onclick="myFunction()">Submit Picture</button><br>
<img id="imagePreview">
First, you should use FileAPI to read the uploaded file's contents.
So you read it, then its contents to base64 and finally you can store them in the localStorage.
Also you need to create a <canvas> element to convert the image to base64.
Here is your code:
HTML:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" accept="image/*" id="uploadImage">
<br>
<button onclick="myFunction()">
Submit Picture
</button>
<br>
<img id="imagePreview">
CSS:
img {
max-width: 300px;
}
JavaScript:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
document.getElementById("uploadImage").addEventListener("change", function() {
if (document.getElementById('uploadImage').files && document.getElementById('uploadImage').files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').attr('src', e.target.result);
}
reader.readAsDataURL(document.getElementById('uploadImage').files[0]); // convert to base64 string
}
});
$("#imgInp").change(function() {
readURL(this);
});
function myFunction() {
bannerImage = document.getElementById('imagePreview');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);
}
Here is a living demo: https://codepen.io/marchmello/pen/rNOLJya
I'm trying to make an image slider. I have an array of objects like this:
var slides = [
{
img: 'images/one.jpg',
text: 'First Image'
},
{
img: 'images/two.jpg',
text: 'Second Image'
}
];
I need to have the functionality to add more images into the image slider. Hence I need to obtain the file path of the image I will be uploading and push that file path into this slides array.
I have gone through this SO answer, which effectively teaches how to upload and display an image, but my needs are different.
HTML
<div id="slide-container">
</div>
<div id="panel-container">
<form>
<label>
<span>Image Text</span>
<input type="text" class="form-control" id="image-related-text">
</label>
<label>
<span>Duration</span>
<input type="text" class="form-control" id="time-duration">
</label>
<div id="d">
<input type="file" id="image-upload">
</div>
<button id="add" disabled="true">Add to Container</button>
</form>
</div>
JS
var global_image_url = "";
// add the image and the relevant text in the slider on click of this button
$('#add').click(function(){
var imageRelatedText = $('#image-related-text').val();
var timeDuration = $('#time-duration').val();
// a new object to be pushed inside the 'slides' array
var temp_obj = {
img: 'nothing for now :|', //this should contain the image url
text: imageRelatedText
};
})
$('#image-upload').change(function(){
global_image_url = readUrl(this);
console.log(global_image_url);
});
// this function gets called when an image file is chosen
function readUrl(input){
var img = $('<img>');
var local_image_url = ""; // thought I would store the file path in this variable
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
local_image_url = JSON.stringify(e.target.result);
img.attr('src', e.target.result);
img.attr('height','100%');
img.attr('width','97%');
}
reader.readAsDataURL(input.files[0]);
}
console.log(local_image_url); // chrome developer tools freezes
return local_image_url;
}
I thought e.target.result would give the url but that's not the case. It's just another object (printed in the console once).
So how do I achieve my requirements?
Thanks!
yes e.target.result will the url, but remember FileReader reader the file content as asynchronous, if you want to output the value, you need to add some callback like :
$('#image-upload').change(function(){
readUrl(this,function(){
console.log(global_image_url);
});
});
// this function gets called when an image file is chosen
function readUrl(input,callback){
var img = $('<img>');
var local_image_url = ""; // thought I would store the file path in this variable
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
typeof callback == 'function' && callback(e.target.result);
local_image_url = JSON.stringify(e.target.result);
img.attr('src', e.target.result);
img.attr('height','100%');
img.attr('width','97%');
}
reader.readAsDataURL(input.files[0]);
}
}
I want to insert an image that a user selects from their local machine using FileReader.readAsDataURL() into multiple <img> elements on a single html page.
Using the example code provided by the MDN docs for FileReader.readAsDataURL(), the image only gets inserted into the first img element, not the rest.
I thought the reason the image is only inserted into the first <img> instance is because the example code uses document.querySelector('img'). However, when I use document.querySelectorAll('img'), it still does not work.
The MDN docs provide a working codepen example that you can see in action. Here is their static code:
<!--html-->
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
and
//js
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
Here is a working codepen of my code, and below is my static code.
<div>
<label>Select an Image</label>
<input type="file" onchange="previewFile()">
</div>
<div>
<img id="small" src="http://placehold.it/900x900"/>
<img id="med" src="http://placehold.it/1200x1200"/>
<img id="large" src="http://placehold.it/1500x1500"/>
</div>
<script>
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>
Can anyone offer some help to get the user selected image to populate all of the <img> elements on the page instead of just the first element?
Not quite sure to correctly understand your need.
If it's like this:
you expect only one file (image) to be selected through your <input>
and you want this unique image to be the same source of all your <img>s
Then below is the way to go:
function previewFile() {
var preview = document.querySelectorAll('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
for (var img in preview) {
preview[img].src = reader.result;
}
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
<div>
<label>Select an Image</label>
<input type="file" onchange="previewFile()">
</div>
<div>
<img id="small" src="http://placehold.it/100x100"/>
<img id="med" src="http://placehold.it/200x200"/>
<img id="large" src="http://placehold.it/300x300"/>
</div>
The main points are:
preview gets all <img>s (as you already tried)
then we use a for() loop to process each of them (here was your lack)
The code will need to iterate over all the files in the file list and then assign each (via Object-URL) to separate image element.
I would suggest the following changes as there is really no need for FileReader at this point. The URL.createObjectURL() can be used with File blobs as well and save us from some headache:
document.querySelector("input[type=file]").onchange = previewFile;
function previewFile() {
var files = this.files; // "this" = input element
var parent = document.querySelector(".imageList"); // parent element
var i = 0, file;
while(file = files[i++]) { // iterate over file list
var img = new Image(); // create new image instance
img.src = (URL || webkitURL).createObjectURL(file); // use File blob directly
parent.appendChild(img); // insert image in DOM
};
}
<div>
<label>Select an Image
<input type="file" multiple> <!-- make sure multiple is enabled -->
</label>
</div>
<div class="imageList"></div>
If you want to replace an image list simply obtain the list of images using querySelectorAll() instead of querySelector(), then replace the sources from the list until one run dry:
//... as before
var img, images = document.querySelectorAll("img");
while((file = files[i]) && (img = images[i++])) { // loop until one runs dry
img.src = (URL || webkitURL).createObjectURL(file); // use File blob directly
};
document.querySelector("input[type=file]").onchange = previewFile;
function previewFile() {
var files = this.files; // "this" = input element
var parent = document.querySelector(".imageList"); // parent element
var i = 0, file;
var img, images = document.querySelectorAll("img");
while((file = files[i]) && (img = images[i++])) { // loop until one runs dry
img.src = (URL || webkitURL).createObjectURL(file); // use File blob directly
};
}
<div>
<label>Select an Image
<input type="file" multiple> <!-- make sure multiple is enabled -->
</label>
</div>
<div class="imageList">
<img id="small" src="http://placehold.it/100x100"/>
<img id="med" src="http://placehold.it/200x200"/>
<img id="large" src="http://placehold.it/300x300"/>
</div>
Tell me, please, how can a photo be inserted to <img>, when I open
<input type = "file"> and choose any file ?
How can I use JS / JQuery ?
Use 'FileReader' object:
$("#yourinput").change(function () {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function (e) {
$("#yourimg").attr("src", e.target.result);
}
reader.readAsDataURL(file);
});
this is my form
<form action="#" enctype="multipart/form-data" method="post" name="..." id="formPhoto" class="fmp">
<input type="file" name="pho" id="photo" class="inph" accept="image/*">
<button type="submit" id="subFormPhoto" class="spp">press here</button>
</form>
and this is my code JS
<script type="text/javascript">
var inputPhoto= document.getElementById('photo');
inputPhoto.onchange=function(){var photo= this.value; photo.onload=function(){alert(this.width+' '+this.height);};};
</script>
my problem is that not visualize alert(this.width+' '+this.height);.
as if not load photo
this.value gives the file name as a string, so your photo.onload function isn't really looking at the photo but just some string. If you alert or console.log photo you will see what I mean.
You may wish to consider the File API, it will work with modern browsers as from HTML 5.
Here's a working example of your code:
var inputPhoto = document.getElementById('photo');
inputPhoto.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
var photo = new Image();
reader.readAsDataURL(file);
reader.onload = function(_file) {
photo.src = _file.target.result;
photo.onload = function() {
alert(this.width + ' ' + this.height);
};
};
};
I have tried to create what I understood from your question
http://jsfiddle.net/qo8ovmhn/
<input type="file" name="pho" id="photo" class="inph" onchange="myFunction()">
<img id="view" src=""></img>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("photo");
var file = x.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(_file) {
var img = document.getElementById("view");
img.setAttribute("src",_file.target.result);
var height = img.offsetHeight;
var width = img.offsetWidth;
alert(width + " X " + height);
};
}
</script>
see if this is what you were looking for.
The change event of the input is called on choosing an image. The image bytes are read and put in an image tag. Then the dimensions of the image are fetched from the height and width of the image component.
You can hide the image by adding a css style of visibility:hidden or opacity:0
Do not give display:none as this will result in height and width of 0px
Finally the dimensions are shown in an alert.