This question already has answers here:
Preview images before upload
(10 answers)
Closed 1 year ago.
I have a code for single Image preview, when we select a file from input field we can see the selected image in preview, but how can i do the same for multiple images preview.
here is my code for single image preview.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview-image')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
<img id="preview-image" class="img-prev rounded" src="#" alt="Upload" onerror=this.src="../assets/images/myfolder/no_image.png" />
<input type="file" name="featured_image" id="customFile" onchange="readURL(this);" required>
Jsfiddle : My Fiddle
You can Check all the things in this answer, and if not cleared, then modify as your need .
$(document).ready(function() {
/*multiple image preview first input*/
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFilesD");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
/*end image preview */
/* Multiple image preview second input*/
$("#mobile").on("change", handleFileSelect);
selDivM = $("#selectFilesM");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
console.log($("#selectFilesM").length);
});
/*multiple image preview*/
var selDiv = "";
// var selDivM="";
var storedFiles = [];
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
var device = $(e.target).data("device");
filesArr.forEach(function(f) {
if (!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function(e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='" + f.name + "' class='selFile' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
if (device == "mobile") {
$("#selectedFilesM").append(html);
} else {
$("#selectedFilesD").append(html);
}
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for (var i = 0, len = storedFiles.length; i < len; i++) {
data.append('files', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handler.cfm', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
function removeFile(e) {
var file = $(this).data("file");
for (var i = 0; i < storedFiles.length; i++) {
if (storedFiles[i].name === file) {
storedFiles.splice(i, 1);
break;
}
}
$(this).parent().remove();
}
#selectedFilesD img,
#selectFilesM img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom: 10px;
}
#userActions input {
width: auto;
margin: auto;
}
#selectFiles img,
#selectedFilesM img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" id="myForm" name="myForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
desktop:
<input data-device="desktop" type="file" id="files" name="files" multiple>
<div id="selectedFilesD"></div>
<br/>
mobile:
<input data-device="mobile" type="file" id="mobile" name="mobile" multiple>
<br/>
<div id="selectedFilesM"></div>
<button type="submit">Submit</button>
</form>
Related
I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo
an example I've uploaded the 3 Image (files), In the preview, I did not like 1 file that has been deleted, rest of the files 2 and
it should upload 2 but when I press submit button 3 files inserting into the database
please help me not working
html code
<form action="" method="post" enctype="multipart/form-data">
<div id="filediv">
<input name="upload[]" type="file" id="upload" multiple="multiple" />
</div>
<input type="submit" value="Upload Image" name="submit"/>
</form>
Jquery code
function deletePreview(ele, i) {
"use strict";
try {
$(ele).parent().remove();
filesToUpload.splice(i, 1);
} catch (e) {
console.log(e.message);
}
}
$("#upload").on('change', function() {
"use strict";
var filesToUpload = [];
if (this.files.length >= 1) {
$("[id^=previewImg]").remove();
$.each(this.files, function(i, img) {
var reader = new FileReader(),
newElement = $("<div id='previewImg" + i + "' class='abcd'><img /></div>"),
deleteBtn = $("<span class='delete' onClick='deletePreview(this, " + i + ")'>delete</span>").appendTo(newElement),
preview = newElement.find("img");
reader.onloadend = function() {
preview.attr("src", reader.result);
preview.attr("alt", img.name);
};
var f = document.getElementById("upload").files[i];
filesToUpload.push(f);
if (img) {
reader.readAsDataURL(img);
} else {
preview.src = "";
}
newElement.appendTo("#filediv");
});
}
});
php code
$total = count($_FILES['upload']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "./upload_files/" . $_FILES['upload']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
}
}
}
Thanks in advance
I Made a Demo for preview image before uploading is as follow.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').attr('src', e.target.result).show();
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadphoto").change(function () {
readURL(this);
$('#preview').show();
});
$('#preview').on("click", function () {
$('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
$('#preview').removeProp('src').hide();
$('#uploadphoto').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="uploadphoto" />
<img id="preview" src="">
But Problem is this is work when i have <img id="preview" src="">
What if i wants preview image in div section.
and remove image from div like
<input type="file" id="uploadphoto" />
<!--PREVIEW IMAGE IN THIS DIV-->
<div id="preview">
and after preview delete image on click.
its easy to understand if your answer in fiddle.
thanks.
Check this snippet it helps,
If i understands correctly you want to remove img tag and show image preview in div section.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo('#preview').width(100).height(100);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadphoto").change(function () {
readURL(this);
$('#preview').show();
});
$('#preview').on("click", function () {
$('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
$('#preview').removeProp('src').hide();
$('#uploadphoto').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="uploadphoto" />
<div id="preview"></div>
try with div background-image in jquery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
// $('#preview').attr('src', e.target.result).show();
$('#preview').css("height", "300px");
$('#preview').css("width", "300px");
$('#preview').css("background-image", "url(" + e.target.result + ")").show();
$('#preview').css("background-size","cover");
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadphoto").change(function() {
readURL(this);
$('#preview').show();
});
$('#preview').on("click", function() {
$('#uploadphoto').replaceWith(selected_photo = $('#uploadphoto').clone(true));
$('#preview').removeProp('src').hide();
$('#uploadphoto').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="uploadphoto" />
<!--<img id="preview" src="">-->
<div id="preview"></div>
Try this
function Preview_Image_Before_Upload(fileinput_id, preview_id) {
var oFReader = new FileReader();
var fileArray = [];
fileArray.push(document.getElementById(fileinput_id).files[0])
fileArray.forEach(function(entry) {
oFReader.readAsDataURL(fileArray[0]);
});
//console.log(fileArray)
// oFReader.readAsDataURL(fileArray[0]);
oFReader.onload = function(oFREvent) {
if (window.FileReader && window.File && window.FileList && window.Blob) {
var elem = document.getElementById("uploadPreview");
elem.src = oFREvent.target.result;
// document.getElementById("placehere").appendChild(elem);
document.getElementById("uploadPreview").innerHTML=elem;
}
};
};
function removeFns(){
//document.getElementById("uploadPreview").innerHTML=null;
document.getElementById('uploadImage').value = ""
document.getElementById('uploadPreview').src = "#";
}
<input type="file" id="uploadImage" onchange="Preview_Image_Before_Upload('uploadImage', 'uploadPreview');" name="termek_file" class="file_input" />
<img id="uploadPreview" onclick="removeFns()" class="uploadPreview" width="100" />
<div id="placehere" class="uploadPreview" width="100">
you can clear the image by using this code
$("preview").remove()
HTM like this :
<input type='file' multiple id="upload-file"/>
<?php
for($i=0;$i<5; $i++) {
?>
<div class="img-container" id="box<?php echo $i ?>">
<button style="display: none;" type="submit" class="btn btn-primary show-button">
<i class="glyphicon glyphicon-edit"></i>
</button>
</div>
<?php
}
?>
Javascript like this :
$(function () {
$(":file").change(function () {
var noOfFiles = this.files.length;
for(var i=0; i < noOfFiles; i++) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[i]);
}
});
});
function imageIsLoaded(e) {
var imgTmpl = '<img height="142" width="162" src='+e.target.result+'>';
var IsImgAdded=false;
$('.img-container').each(function(){
if($(this).find('img').length==0 && IsImgAdded==false){
$(this).append(imgTmpl);
IsImgAdded=true;
$(this).find('.show-button').show();
}
});
};
$(".show-button").click(function(){
$("#upload-file").click();
});
Demo and full code like this : http://phpfiddle.org/main/code/1g8t-h5kn
I try like that. But it does not fit
Should when I edit image on the box 2, it will change image on the box 2. Not box 3
How can I solve this issue?
You need to create a var to set the actual edited container than after the upload launch the function, check if the variable has a value different than null and append the img in the right place.
WORKING FIDDLE HERE: https://codepen.io/VLK_STUDIO/pen/wdQPRL
$(function() {
$(":file").change(function() {
var noOfFiles = this.files.length;
for (var i = 0; i < noOfFiles; i++) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[i]);
}
});
});
var actualEdited = "";
function imageIsLoaded(e) {
var imgTmpl = '<img height="142" width="162" src=' + e.target.result + ">";
var IsImgAdded = false;
$(".img-container").each(function() {
if ($(this).find("img").length == 0 && IsImgAdded == false) {
if (actualEdited == "") {
$(this).append(imgTmpl);
$(this).find(".show-button").show();
IsImgAdded = true;
return false;
} else {
$(actualEdited).find("img").remove();
$(actualEdited).append(imgTmpl);
$(actualEdited).find(".show-button").show();
actualEdited = "";
return false;
}
} else {
if (actualEdited != "") {
$(actualEdited).find("img").remove();
$(actualEdited).append(imgTmpl);
$(actualEdited).find(".show-button").show();
actualEdited = "";
return false;
}
}
});
}
$(".show-button").click(function() {
$("#upload-file").click();
actualEdited = $(this).parent();
});
.img-container {
width: 100px;
border: 1px solid black;
height: 100px;
margin: 20px;
display: inline-block;
}
img {
display: block;
width: 100%;
height: auto;
}
.show-button {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="upload-file" type="file">
<div class="img-container">
<div class="show-button">click
</div>
</div>
<div class="img-container">
<div class="show-button">click
</div>
</div>
<div class="img-container">
<div class="show-button">click
</div>
</div>
<div class="img-container">
<div class="show-button">click
</div>
</div>
$(function () {
$(":file").change(function () {
var noOfFiles = this.files.length;
for(var i=0; i < noOfFiles; i++) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[i]);
}
});
});
function imageIsLoaded(e) {
var imgTmpl = '<img height="142" width="162" src='+e.target.result+'>';
var IsImgAdded=false;
$('.img-container').each(function(){
if($(this).find('img').length==0 && IsImgAdded==false){
$(this).append(imgTmpl);
IsImgAdded=true;
$(this).find('.show-button').show();
} else {
if ($(this).id == sessionStorage.getItem('blockid')){
$(this).append(imgTmpl);
IsImgAdded=true;
$(this).find('.show-button').show();
}
}
});
};
$(".show-button").click(function(){
sessionStorage.setItem('blockid', $(this).id);
$("#upload-file").click();
});
You're forggeting to identify the edited blocks. I warn you this is not the best approach, but the faster one. Bind one object action to another is confusing and poor practice, i advise you to use better js functions/closures to get what you want with proper form.
In my HTML form I have input filed with type file for example :
<input type="file" multiple>
Then I'm selecting multiple files by clicking that input button.
Now I want to show preview of selected images before submitting form . How to do that in HTML 5?
Here's a quick example that makes use of the URL.createObjectURL to render a thumbnail by setting the src attribute of an image tag to a object URL:
The html code:
<input accept="image/*" type="file" id="files" />
<img id="image" />
The JavaScript code:
document.getElementById('files').onchange = function () {
var src = URL.createObjectURL(this.files[0])
document.getElementById('image').src = src
}
The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:
function handleFileSelect (evt) {
// Loop through the FileList and render image files as thumbnails.
for (const file of evt.target.files) {
// Render thumbnail.
const span = document.createElement('span')
const src = URL.createObjectURL(file)
span.innerHTML =
`<img style="height: 75px; border: 1px solid #000; margin: 5px"` +
`src="${src}" title="${escape(file.name)}">`
document.getElementById('list').insertBefore(span, null)
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" accept="image/*" id="files" multiple />
<output id="list"></output>
Here I did with jQuery using FileReader API.
Html Markup:
<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>
jQuery:
Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message
$("#fileUpload").on('change', function () {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="',
e.target.result,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" multiple />
<output id="list"></output>
For background images, make sure to use url()
node.backgroundImage = 'url(' + e.target.result + ')';
Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).
Don't forget to validate image extension.
<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');
const handle_file_preview = (e) => {
let files = e.target.files;
let length = files.length;
for(let i = 0; i < length; i++) {
let image = document.createElement('img');
// use the DOMstring for source
image.src = window.URL.createObjectURL(files[i]);
image_preview.appendChild(image);
}
}
file_input.addEventListener('change', handle_file_preview);