I'm looking for a simple way for a user to select a list of files for upload and have them display on screen before he decides to upload them.
This is the sort of logic I've been trying:
function printFiles(){
var inp = document.getElementById('selected');
for (var i = 0; i < inp.files.length; ++i) {
var img = new Image();
var name = inp.files.item(i).name;
img.src = name;
document.body.appendChild(img);
}
<head>
<title>Upload new File</title>
</head>
<body>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p>
<input type=file name=file id=selected onclick=printFiles() multiple>
<input type=submit value=Upload>
</p>
</form>
</body>
This doesn't work and when I print the variable inp to the console, it shows null, as it's null until selected.
Is there a way to pass the file names to the function and display them on the page only after the user has clicked 'choose files' and then 'open'?
you have an error inside the loop, on inp.files.item you shoul use [i] instead of (i), this is and array of selected files on the input tag
function printFiles(){
var inp = document.getElementById('selected');
for (var i = 0; i < inp.files.length; ++i) {
var img = new Image();
// var name = inp.files.item(i).name;
var name = inp.files.item[i].name;
img.src = name;
document.body.appendChild(img);
}
<head>
<title>Upload new File</title>
</head>
<body>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<p>
<input type=file name=file id=selected onclick=printFiles() multiple>
<input type=submit value=Upload>
</p>
</form>
</body>
Here is an example of how to do it with javascript FileReader Api
function printFiles(){
var inp = document.getElementById('selected');
for (var i = 0; i < inp.files.length; ++i) {
displayImage(inp.files[i]);
}
}
function displayImage(file){
var reader = new FileReader();
reader.readAsDataURL(file);
reader.addEventListener('load', function(){
var img = new Image();
img.src = reader.result;
document.body.appendChild(img);
});
}
Related
How can I make this text that is button allow you to input pictures but disappear when picture is uploaded and comes back if you don't chose a photo?
<label class="btn btn-primary">
<img id="uploadPreview" style="width:200px;height:100px; text-align:right ; border:1px black;" />
<p class="image">Click to upload your pictures</p> <input type="file"id="uploadImage" name="myPhoto" style="display: none;"onchange="PreviewImage();" >
</label>
<script >
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
};
</script>
You can update the button visibility style on the onchange="PreviewImage();" event.
function PreviewImage() {
var oFReader = new FileReader();
var img = document.getElementById("uploadImage");
var btn = document.getElementsByClassName("image")[0];
if (img.files[0]){
btn.style.display = "none"; // hide button
oFReader.readAsDataURL(img.files[0]);
}else{
// uncomment this part if you want to clear image when you don't choose a photo
/* document.getElementById("uploadPreview").removeAttribute('src');
img.value = "";
btn.style.display = "block"; */
}
...
Basically, I have a simple webpage with two text fields, and a button to choose an image from the computer. What I need to happen, is for the user to pick a photo, fill in the "artist" and "text" field, press the "Add image" button. This should then add all three items to an array, and display both the image in a div, and the text in an "li" list item.
At the moment, the image works, and will display on the screen when the button is pressed, the text seems to get pushed into the array, but no matter what I do, I can't get the text to display on the web page. I also couldn't get the image to display if I turned the array into objects, which is why I've split the pushing of the text to a separate function.
Either way, whatever I try, either breaks the image display, or breaks the text display. I can't get both to display on the page. I am trying to make it so whenever a new image and text is added, it will all display one after another sort of like this:
[album cover]
[text]
[album cover]
[text]
And this would carry on down the screen as you keep adding more. Can someone please tell me where I'm going wrong with this. Thanks.
var info = {
myImages: [],
addImage: function(imageBlob) {
this.myImages.push(imageBlob);
},
addInfo: function(artist, title) {
this.myImages.push({
artist: artist,
title: title
});
},
redrawImages: function() {
var divForImages = document.getElementById('myImages');
divForImages.innerHTML = '';
this.myImages.forEach((imageBlob) => {
var img = document.createElement('img');
img.style.width = "200px";
img.style.height = "200px";
img.src = URL.createObjectURL(imageBlob);
divForImages.appendChild(img);
});
},
redrawInfo: function() {
var ul = document.querySelector('ul');
this.myImages.forEach(function (item) {
let li = document.createElement('li');
ul.appendChild(li);
li.innerHTML += item;
});
}
}
var handlers = {
addImageAndRedraw: function() {
var fileInput = document.getElementById('fileInput');
var artistField = document.getElementById('artistField');
var titleField = document.getElementById('titleField');
if (fileInput.files.length === 1) {
info.addImage(fileInput.files[0]);
info.addInfo(artistField.value, titleField.value);
info.redrawImages();
info.redrawInfo();
}
}
}
var button = document.getElementById('button');
button.addEventListener('click', handlers.addImageAndRedraw);
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My images</h1>
<input id="fileInput" type="file" accept="image/*" multiple="false" value="Select image">
<input id="button" type="button" value="Add image and redraw">
<div>
<input id="artistField" type="text" placeholder="artist">
<input id="titleField" type="text" placeholder="title">
</div>
<hr>
<div id="myImages">
</div>
<ul></ul>
<script src="album.js"></script>
</body>
</html>
You're adding the info to the same array as the images, so it will end up like [image, info, image, info] etc.. You're better off adding an object that contains both the image and the info, and then treating it as a single object when you add the contents to the page, rather than adding the images and text in separate functions. Also, you're not clearing the info list, so it would grow exponentially.
Here's a modified example, just after tweaking the bits I mentioned above...
var info = {
myInfo: [],
add: function(imageBlob, artist, title) {
this.myInfo.push({
image: imageBlob,
artist: artist,
title: title
});
},
redraw: function() {
var divForImages = document.getElementById('myImages');
divForImages.innerHTML = '';
var ul = document.querySelector('ul');
ul.innerHTML = "";
this.myInfo.forEach((info) => {
var img = document.createElement('img');
img.style.width = "200px";
img.style.height = "200px";
img.src = URL.createObjectURL(info.image);
divForImages.appendChild(img);
let li = document.createElement('li');
ul.appendChild(li);
li.innerHTML = info.artist + " - " + info.title;
});
},
}
var handlers = {
addImageAndRedraw: function() {
var fileInput = document.getElementById('fileInput');
var artistField = document.getElementById('artistField');
var titleField = document.getElementById('titleField');
if (fileInput.files.length === 1) {
info.add(fileInput.files[0], artistField.value, titleField.value);
info.redraw();
}
}
}
var button = document.getElementById('button');
button.addEventListener('click', handlers.addImageAndRedraw);
<h1>My images</h1>
<input id="fileInput" type="file" accept="image/*" multiple="false" value="Select image">
<input id="button" type="button" value="Add image and redraw">
<div>
<input id="artistField" type="text" placeholder="artist">
<input id="titleField" type="text" placeholder="title">
</div>
<hr>
<div id="myImages"></div>
<ul></ul>
I have found a code on internet to upload multiple images. While you select the image, it will show the selected image just below as preview, now the problem is what if I selected the wrong image and I want to remove that particular image, also no more than 4 image should be allowed
hope you get what I want to say below is the code
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
and jquery for the code is
$(function() {
// Multiple images preview in browser
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);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
The file list of HTML5 file input is readonly. So it's not possible to remove a single file out from a multiple file selection.
It's perfectly fine to empty a file input by resetting the form. You just can't modify it. So if you use 4 seperate single file selections, it's a simple matter of clearing the one that's being removed by the user:
HTML:
<form>
<input type="file" name='images[]' class="gallery-photo-add" id='image1' />
<input type="file" name='images[]' class="gallery-photo-add" id='image2' />
<input type="file" name='images[]' class="gallery-photo-add" id='image3' />
<input type="file" name='images[]' class="gallery-photo-add" id='image4' />
</form>
<div class="gallery"></div>
JS:
$(function() {
// Multiple images preview in browser
var imagesPreview = function(placeToInsertImagePreview) {
// Empty preview so we can safely rebuild it
$(placeToInsertImagePreview).empty();
// Get all files
var elems = document.getElementsByClassName("gallery-photo-add");
// Loop through each file and append them to the preview if available
for (i = 0; i < elems.length; i++) {
if (elems[i].files.length != 0) {
var reader = new FileReader();
var id = $(elems[i]).attr('id');
reader.onload = (function(id) {
return function(e){
$($.parseHTML('<img>')).attr({
'src' : e.target.result,
'data-id' : id
}).appendTo(placeToInsertImagePreview);
}
})(id);
reader.readAsDataURL(elems[i].files[0]);
}
}
};
// Temporarely wrap a form element around the input to reset it
window.reset = function(e) {
e.wrap("<form>").closest('form').get(0).reset();
e.unwrap();
}
$('div.gallery').on('click', 'img', function() {
var id = $(this).attr("data-id");
reset($('#'+id));
$(this).remove();
});
$('.gallery-photo-add').on('change', function() {
imagesPreview('div.gallery');
});
});
You can test it here: https://jsfiddle.net/81nytqsc/2/
$('div.gallery').on('click','img',function(){
var files= $('#gallery-photo-add).get(0).files;
for(i=0;i<files.length;i++){
if(files[i]==$(this).attr('src')){
files= jQuery.grep(files, function(value) {
return value != files[i];
}
}
}
$(this).remove();
});
I have the 2 file upload field and each one have the 'Clear' Button.
When I upload the files and click one of the ''Clear' Button then all the
file upload are clear. but I need to clear one file.
Pleas see my code
<input type="file" id="control1"/>
<button id="clear1">Clear</button>
<input type="file" id="control2"/>
<button id="clear2">Clear</button>
var control = $("#control1");
$("#clear1").on("click", function () {
control1.replaceWith( control1 = control1.clone( true ) );
});
var control2 = $("#control2");
$("#clear2").on("click", function () {
control2.replaceWith( control2 = control2.clone( true ) );
});
Try this:
<script type="text/javascript">
function clear2() {
var fileUpload = document.getElementById("<%=control2.ClientID %>");
var id = fileUpload.id;
var name = fileUpload.name;
//Create a new FileUpload element.
var newFileUpload = document.createElement("INPUT");
newFileUpload.type = "FILE";
//Append it next to the original FileUpload.
fileUpload.parentNode.insertBefore(newFileUpload, fileUpload.nextSibling);
//Remove the original FileUpload.
fileUpload.parentNode.removeChild(fileUpload);
//Set the Id and Name to the new FileUpload.
newFileUpload.id = id;
newFileUpload.name = name;
return false;
}
function clear1() {
var fileUpload = document.getElementById("<%=control1.ClientID %>");
var id = fileUpload.id;
var name = fileUpload.name;
//Create a new FileUpload element.
var newFileUpload = document.createElement("INPUT");
newFileUpload.type = "FILE";
//Append it next to the original FileUpload.
fileUpload.parentNode.insertBefore(newFileUpload, fileUpload.nextSibling);
//Remove the original FileUpload.
fileUpload.parentNode.removeChild(fileUpload);
//Set the Id and Name to the new FileUpload.
newFileUpload.id = id;
newFileUpload.name = name;
return false;
}
</script>
<input type="file" id="control1"/>
<input id="Button1" type="button" value="clickme" onclick="clear1();" />
<input type="file" id="control2"/>
<input id="clickMe" type="button" value="clickme" onclick="clear2();" />
The following code works as per my requirement in firefox. but coming to IE 8, except file browsing nothing happening. Can any one check it out for issues pls?any thing need to add in the first line?
thanks in advance.
the code is
<!DOCTYPE html>
<html>
<head>
<script>
function loadfile(input) {
var theRange = null;
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('mytext').value = e.target.result;
var msg = e.target.result;
}
reader.readAsText(input.files[0]);
}
</script>
<script type="text/javascript">
function check1()
{
var str = document.getElementById('mytext').value;
var names=document.getElementById('username').value ;
var n = str.search(names);
if(n==-1)
{
alert("not found");
}
else
{
alert("user name found");
var str1 = document.getElementById('mytext').value;
var str_array = str1.split(',');
var ind = str_array.indexOf(names);
//alert("I worked");
var kname = str_array[ind];
alert(kname);
var i=0;
for (i = ind; i< ind+8; i++ )
{
k=0;
}
var print = str_array[i];
var print_array = print.split('\n');
alert(print_array[0]);
}
}
</script>
</head>
<body>
Select the file to display:
<input type="file" onchange="loadfile(this)">
<br></br>
<textarea rows="20" cols="100" id="mytext"></textarea>
<br></br>
<form> Enter UserName: <input type="text" id="username" name="username"> <b></form>
<br></br>
<input type="button" onclick="check1();" value="Search" />
<pre id="output"></pre>
</body>
</html>
IE8 does not have support for FileReader.
A great site to find out if a browser supports certain features or not is http://caniuse.com/
In your case you could've searched for: http://caniuse.com/#search=filereader