I'm using touchTouch lightbox library in order to preview the images in a lightbox for a post that user wants to send.
This library is used on my back-end and works flawlessly (since the images are in a folder already), but in the front-end there is a form where the user may upload up to 20 images. The images will show their preview after the user has uploaded them (but before they have sent the form) and I want them to be clickable which would open a lightbox library.
The problem is that the library can't find the images location because they are not uploaded just yet.
I thought about using ajax to upload the images into a temporary folder and then remove the folder and its content once the form is submitted. Could this work (without refreshing the page or submitting the form), or are there any better alternative solutions for this?
JavaScript code to upload the files and show their preview + initialize lightbox library upon loading:
function ImgUpload() {
var imgWrap = "";
var imgArray = [];
$('.upload__inputfile').each(function () {
$(this).on('change', function (e) {
imgWrap = $(this).closest('.upload__box').find('.upload__img-wrap');
var maxLength = $(this).attr('data-max_length');
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
var iterator = 0;
filesArr.forEach(function (f, index) {
if (!f.type.match('image.*')) {
return;
}
if (imgArray.length > maxLength) {
return false
} else {
var len = 0;
for (var i = 0; i < imgArray.length; i++) {
if (imgArray[i] !== undefined) {
len++;
}
}
if (len > maxLength) {
return false;
} else {
imgArray.push(f);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<div class='upload__img-box'><a href='" + f.name + "' class='light-box' data-group='gallery'><div style='background-image: url(" + e.target.result + ")' data-number='" + $(".upload__img-close").length + "' data-file='" + f.name + "' class='img-bg'><div class='upload__img-close'></div></div></a></div>";
imgWrap.append(html);
iterator++;
touchTouch(document.body.querySelectorAll('.light-box')); // Initialize the lightbox library
// Ajax script here to upload the images to a temporary folder?
}
reader.readAsDataURL(f);
}
}
});
});
});
Basically you could create a data-url from an uploaded image (before uploaded) which will allow you to access it locally and treat it like it was a regular image.
imgInp.onchange = evt => {
const [...files] = imgInp.files
if (files) {
files.forEach(function(file) {
var img = new Image();
img.src = URL.createObjectURL(file)
img.style.width = "200px"
container.appendChild(img)
// do your touchTouch initialization on the new elements
// touchTouch(img);
img.onclick = function() {
alert('lightbox');
}
})
}
}
<form>
<p>Choose Images, then click for lightbox.</p>
<input accept="image/*" type='file' id="imgInp" multiple />
</form>
<div id="container">
</div>
Let's try with given code (not tested):
ImgUpload();
function ImgUpload() {
var imgWrap = "";
var imgArray = [];
$('.upload__inputfile').each(function() {
$(this).on('change', function(e) {
imgWrap = $(this).closest('.upload__box').find('.upload__img-wrap');
var maxLength = $(this).attr('data-max_length');
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
var iterator = 0;
filesArr.forEach(function(f, index) {
if (!f.type.match('image.*')) {
return;
}
if (imgArray.length > maxLength) {
return false
} else {
var len = 0;
for (var i = 0; i < imgArray.length; i++) {
if (imgArray[i] !== undefined) {
len++;
}
}
if (len > maxLength) {
return false;
} else {
imgArray.push(f);
var object_url = URL.createObjectURL(f)
var html = "<div class='upload__img-box'><a href='" + f.name + "' class='light-box' data-group='gallery'><div style='background-image: url(" + object_url + ")' data-number='" + $(".upload__img-close").length + "' data-file='" + f.name + "' class='img-bg'><div class='upload__img-close'></div></div></a></div>";
imgWrap.append(html);
iterator++;
setTimeout(function() {
touchTouch(document.body.querySelectorAll('.light-box')); // Initialize the lightbox library
});
// Ajax script here to upload the images to a temporary folder?
}
}
});
});
});
}
<form>
<p>Choose Images, then click for lightbox.</p>
<input accept="image/*" type='file' id="imgInp" class="upload__inputfile" multiple />
</form>
<div id="container">
</div>
Attempt to convert the data obtained from the File interface to Base64 or DataURL.then set img src='data:image/png;base64str'
are there any better alternative solutions for this?
Yes! I would recommend these js libraries
Filepond by PQINA and Dropzone.js
Be advised that they both have image preview but not lightbox feature. But with Dropzone.js, this Stack Overflow thread might help How to add popup image in to dropzone thumbnail?
Is there anyway where pdf/image file can auto preview/shown in iframe before uploading without need click on preview button?
function PreviewImage() {
pdffile=document.getElementById("uploadPDF").files[0];
pdffile_url=URL.createObjectURL(pdffile);
$('#viewer').attr('src',pdffile_url);
}
<form name=f1 method=post enctype="multipart/form-data">
<input id="uploadPDF" type="file" name="file"/>
<input type="button" value="Preview" onclick="PreviewImage();" />
<div style="clear:both">
<iframe id="viewer" frameborder="0" scrolling="no" width="300" height="200"></iframe>
</div>
<button type="submit" name="submit" class="btn btn-success btn-sm">
<i class="fa fa-dot-circle-o"></i> Add
</button>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
You have an input, check the onChange and then make a
src= URL.createObjectURL(event.target.files[0])
to create URL: and then use it to preview with embed
<embed
src=src
width="250"
height="200">
Read more here https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed
you can use javascript pdf library like this one (i'm using pdf.js) from this link :
https://mozilla.github.io/pdf.js/examples/index.html#interactive-examples
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';
$("#myPdf").on("change", function(e){
var file = e.target.files[0]
if(file.type == "application/pdf"){
var fileReader = new FileReader();
fileReader.onload = function() {
var pdfData = new Uint8Array(this.result);
// Using DocumentInitParameters object to load binary data.
var loadingTask = pdfjsLib.getDocument({data: pdfData});
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');
// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function(page) {
console.log('Page loaded');
var scale = 1.5;
var viewport = page.getViewport({scale: scale});
// Prepare canvas using PDF page dimensions
var canvas = $("#pdfViewer")[0];
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
console.log('Page rendered');
});
});
}, function (reason) {
// PDF loading error
console.error(reason);
});
};
fileReader.readAsArrayBuffer(file);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<input type="file" id="myPdf" /><br>
<canvas id="pdfViewer"></canvas>
How to preview PDF ,excel and Image before upload in pop window.
I have done something for me issue its working fine for me . also have added the blank pop once you are going to choose next file.
I have created for MVC .
JavaScript:
<script type="text/javascript" src="https://unpkg.com/xlsx#0.15.1/dist/xlsx.full.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<script>
// tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://mozilla.github.io/pdf.js/build/pdf.worker.js';
$("#Document").on("change", function (e)
{
$("#dialog").dialog({
width: 700,
height: 500,
dialogClass: "dialog-full-mode" /*must to add this class name*/
});
var file = e.target.files[0]
if (file.type == "application/pdf")
{
var fileReader = new FileReader();
fileReader.onload = function () {
var pdfData = new Uint8Array(this.result);
// Using DocumentInitParameters object to load binary data.
var loadingTask = pdfjsLib.getDocument({ data: pdfData });
loadingTask.promise.then(function (pdf) {
console.log('PDF loaded');
// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function (page) {
console.log('Page loaded');
var scale = 1.5;
var viewport = page.getViewport({ scale: scale });
// Prepare canvas using PDF page dimensions
var canvas = $("#pdfViewer")[0];
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.promise.then(function () {
console.log('Page rendered');
});
});
}, function (reason) {
// PDF loading error
console.error(reason);
});
};
fileReader.readAsArrayBuffer(file);
}
//$('#excel_data').empty("");
if (file.type == "image/jpeg")
{
debugger
document.getElementById("img1").style.display = "block";
var reader = new FileReader();
reader.onload = function () {
var output = document.getElementById('img1');
output.src = reader.result;
};
reader.readAsDataURL(e.target.files[0]);
// $('#img1').attr("src", "");
}
if (file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onload = function (e) {
var data = new Uint8Array(reader.result);
var work_book = XLSX.read(data, { type: 'array' });
var sheet_name = work_book.SheetNames;
var sheet_data = XLSX.utils.sheet_to_json(work_book.Sheets[sheet_name[0]], { header: 1 });
if (sheet_data.length > 0) {
var table_output = '<table class="table table-striped table-bordered">';
for (var row = 0; row < sheet_data.length; row++) {
table_output += '<tr>';
for (var cell = 0; cell < sheet_data[row].length; cell++) {
if (row == 0) {
table_output += '<th>' + sheet_data[row][cell] + '</th>';
}
else {
table_output += '<td>' + sheet_data[row][cell] + '</td>';
}
}
table_output += '</tr>';
}
table_output += '</table>';
document.getElementById('excel_data').innerHTML = table_output;
}
}
}
});
</script>
#Html.LabelFor(model => model.Document, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.Document, new { htmlAttributes = new {type="file",accept=".xlsx,.xls,image/*,.pdf", #class = "form-control" } })
#Html.ValidationMessageFor(m => m.Document, "", new { #class = "text-danger" })
<div id="dialog" style="display: none; width:auto; ">
<img src="" id="img1" class="img1" style="display:none;"><br>
<div id="excel_data" class="mt-5" ></div>
<canvas id="pdfViewer" ></canvas>
</div>
I have a page with four images for the user to select. I want the user to be able to preview each image on the site before upload.
The JavaScript code below works for only one image but I would like it to work for multiple images uploaded via <input type="file">.
What will be the best way to do this?
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#output').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#file-input").change(function () {
readURL(this);
});
Here is jQuery version for you. I think it more simplest thing.
$(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');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
Add the multiple attribute to your HTMLInputElement
Add the accept attribute to your HTMLInputElement
To filter your files selection to images only, use accept="image/*", or a comma separated MIME list: accept="image/png, image/jpeg"
Use FileReader.readAsDataURL to get the Base64 string,
or URL.createObjectURL to get the file Blob object
Using FileReader.readAsDataURL
The asynchronous way to read the image data is by using FileReader API and its readAsDataURL method which returns a Base64 String:
const preview = (file) => {
const fr = new FileReader();
fr.onload = () => {
const img = document.createElement("img");
img.src = fr.result; // String Base64
img.alt = file.name;
document.querySelector('#preview').append(img);
};
fr.readAsDataURL(file);
};
document.querySelector("#files").addEventListener("change", (ev) => {
if (!ev.target.files) return; // Do nothing.
[...ev.target.files].forEach(preview);
});
#preview img { max-height: 100px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
Async strategy:
Due to the asynchronous nature of FileReader, you could implement an async/await strategy:
// DOM utility functions:
const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, props) => Object.assign(document.createElement(tag), props);
// Preview images before upload:
const elFiles = el("#files");
const elPreview = el("#preview");
const previewImage = (props) => elPreview.append(elNew("img", props));
const reader = (file, method = "readAsDataURL") => new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onload = () => resolve({ file, result: fr.result });
fr.onerror = (err) => reject(err);
fr[method](file);
});
const previewImages = async(files) => {
// Remove existing preview images
elPreview.innerHTML = "";
let filesData = [];
try {
// Read all files. Return Array of Promises
const readerPromises = files.map((file) => reader(file));
filesData = await Promise.all(readerPromises);
} catch (err) {
// Notify the user that something went wrong.
elPreview.textContent = "An error occurred while loading images. Try again.";
// In this specific case Promise.all() might be preferred over
// Promise.allSettled(), since it isn't trivial to modify a FileList
// to a subset of files of what the user initially selected.
// Therefore, let's just stash the entire operation.
console.error(err);
return; // Exit function here.
}
// All OK. Preview images:
filesData.forEach(data => {
previewImage({
src: data.result, // Base64 String
alt: data.file.name // File.name String
});
});
};
elFiles.addEventListener("change", (ev) => {
if (!ev.currentTarget.files) return; // Do nothing.
previewImages([...ev.currentTarget.files]);
});
#preview img { max-height: 100px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
Using URL.createObjectURL
The synchronous way to read the image is by using the URL API and its createObjectURL method which returns a Blob:
const preview = (file) => {
const img = document.createElement("img");
img.src = URL.createObjectURL(file); // Object Blob
img.alt = file.name;
document.querySelector('#preview').append(img);
};
document.querySelector("#files").addEventListener("change", (ev) => {
if (!ev.target.files) return; // Do nothing.
[...ev.target.files].forEach(preview);
});
#preview img { max-height: 120px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
Although looks much simpler, it has implications on the main thread due to its synchronicity, and requires you to manually use (when possible) URL.revokeObjectURL in order to free up memory:
// Remove unused images from #preview? Consider also using
URL.revokeObjectURL(someImg.src); // Free up memory space
jQuery example:
A jQuery implementation of the above FileReader.readAsDataURL() example:
const preview = (file) => {
const fr = new FileReader();
fr.onload = (ev) => {
$('#preview').append($("<img>", {src: fr.result, alt: file.name}));
};
fr.readAsDataURL(file);
};
$("#files").on("change", (ev) => {
if (!ev.target.files) return; // Do nothing.
[...ev.target.files].forEach(preview);
});
#preview img { max-height: 120px; }
<input id="files" type="file" accept="image/*" multiple>
<div id="preview"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
Additional read:
File API — Using files from web applications (MDN)
readAsDataURL (MDN)
FileReader result (MDN)
Promise.all() (MDN)
Preview Image, get file size, image height and width before upload
Tips:
Besides using the HTMLInputElement attribute accept, if you want to make sure within JavaScript that a file is-of-type, you could:
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
// Not a valid image
}
or like:
if (!/^image\//i.test(file.type)) {
// File is not of type Image
}
function previewMultiple(event){
var saida = document.getElementById("adicionafoto");
var quantos = saida.files.length;
for(i = 0; i < quantos; i++){
var urls = URL.createObjectURL(event.target.files[i]);
document.getElementById("galeria").innerHTML += '<img src="'+urls+'">';
}
}
#galeria{
display: flex;
}
#galeria img{
width: 85px;
height: 85px;
border-radius: 10px;
box-shadow: 0 0 8px rgba(0,0,0,0.2);
opacity: 85%;
}
<input type="file" multiple onchange="previewMultiple(event)" id="adicionafoto">
<div id="galeria">
</div>
Just use FileReader.readAsDataURL()
HTML:
<div id='photos-preview'></div>
<input type="file" id="fileupload" multiple (change)="handleFileInput($event.target.files)" />
JS:
function handleFileInput(fileList: FileList) {
const preview = document.getElementById('photos-preview');
Array.from(fileList).forEach((file: File) => {
const reader = new FileReader();
reader.onload = () => {
var image = new Image();
image.src = String(reader.result);
preview.appendChild(image);
}
reader.readAsDataURL(file);
});
}
DEMO
$(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');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
function previewImages() {
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
<input id="file-input" type="file" multiple>
<div id="preview"></div>
function previewImages() {
var preview = document.querySelector('#preview');
if (this.files) {
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file) {
// Make sure `file.name` matches our extensions criteria
if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
return alert(file.name + " is not an image");
} // else...
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.height = 100;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#file-input').addEventListener("change", previewImages);
<input id="file-input" type="file" multiple>
<div id="preview"></div>
<script type="text/javascript">
var upcontrol = {
queue : null, // upload queue
now : 0, // current file being uploaded
start : function (files) {
// upcontrol.start() : start upload queue
// WILL ONLY START IF NO EXISTING UPLOAD QUEUE
if (upcontrol.queue==null) {
// VISUAL - DISABLE UPLOAD UNTIL DONE
upcontrol.queue = files;
document.getElementById('uploader').classList.add('disabled');
// PREVIEW UPLOAD IMAGES
upcontrol.preview();*enter code here*
//PROCESS UPLOAD ON CLICK
$('#add_files').on('click', function() {
upcontrol.run();
});
}
},
preview : function() {
//upcontrol.preview() : preview uploading file
if (upcontrol.queue) {
var filesAmount = upcontrol.queue.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
var fimg = document.createElement('img')
fimg.src = event.target.result,
fimg.classList = "col-sm-6 col-md-6 col-lg-4 float-left center",
document.getElementById('gallery').appendChild(fimg);
}
reader.readAsDataURL(upcontrol.queue[i]);
}
}
},
run : function () {
// upcontrol.run() : proceed upload file
var xhr = new XMLHttpRequest(),
data = new FormData();
data.append('file-upload', upcontrol.queue[upcontrol.now]);
xhr.open('POST', './lockeroom/func/simple-upload.php', true);
xhr.onload = function (e) {
// SHOW UPLOAD STATUS
var fstat = document.createElement('div'),
txt = upcontrol.queue[upcontrol.now].name + " - ";
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// SERVER RESPONSE
txt += xhr.responseText;
} else {
// ERROR
txt += xhr.statusText;
}
}
fstat.innerHTML = txt;
document.getElementById('upstat').appendChild(fstat);
// UPLOAD NEXT FILE
upcontrol.now++;
if (upcontrol.now < upcontrol.queue.length) {
upcontrol.run();
}
// ALL DONE
else {
upcontrol.now = 0;
upcontrol.queue = null;
document.getElementById('uploader').classList.remove('disabled');
}
};
xhr.send(data);
}
};
window.addEventListener("load", function () {
// IF DRAG-DROP UPLOAD SUPPORTED
if (window.File && window.FileReader && window.FileList && window.Blob) {
/* [THE ELEMENTS] */
var uploader = document.getElementById('uploader');
/* [VISUAL - HIGHLIGHT DROP ZONE ON HOVER] */
uploader.addEventListener("dragenter", function (e) {
e.preventDefault();
e.stopPropagation();
uploader.classList.add('highlight');
});
uploader.addEventListener("dragleave", function (e) {
e.preventDefault();
e.stopPropagation();
uploader.classList.remove('highlight');
});
/* [UPLOAD MECHANICS] */
// STOP THE DEFAULT BROWSER ACTION FROM OPENING THE FILE
uploader.addEventListener("dragover", function (e) {
e.preventDefault();
e.stopPropagation();
});
// ADD OUR OWN UPLOAD ACTION
uploader.addEventListener("drop", function (e) {
e.preventDefault();
e.stopPropagation();
uploader.classList.remove('highlight');
upcontrol.start(e.dataTransfer.files);
});
}
// FALLBACK - HIDE DROP ZONE IF DRAG-DROP UPLOAD NOT SUPPORTED
else {
document.getElementById('uploader').style.display = "none";
}
});
</script>
i used somthing like this and i got the best result and easy to understand.
function appendRows(){
$i++;
var html='';
html+='<div id="remove'+$i+'"><input type="file" name="imagefile[]" accept="image/*" onchange="appendloadFile('+$i+')"><img id="outputshow'+$i+'" height="70px" width="90px"><i onclick="deleteRows('+$i+')" class="fas fa-trash-alt"></i></div>';
$("#appendshow").append(html);
}
function appendloadFile(i){
var appendoutput = document.getElementById('outputshow'+i+'');
appendoutput.src = URL.createObjectURL(event.target.files[0]);
}
https://stackoverflow.com/a/59985954/8784402
ES2017 Way
// convert file to a base64 url
const readURL = file => {
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = e => res(e.target.result);
reader.onerror = e => rej(e);
reader.readAsDataURL(file);
});
};
// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);
const preview = async event => {
const file = event.target.files[0];
const url = await readURL(file);
img.src = url;
};
fileInput.addEventListener('change', preview);
$(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');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery">
$(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');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery">
I have a file upload element:
<input type="file" name='image1' id='image1'>
Then i have a button:
<button onclick="addphotos()">Add photos</button>
The addphotos() function is:
function addphotos() {
var file1 = document.getElementById('image1').files[0];
var img1=file1.name.split(/(\\|\/)/g).pop();
var pic1 = "url(" + file1 + ")";
document.getElementById("right").style.backgroundImage=pic1;
}
As far as I know, the last line's syntax should be correct but I think I am missing something there. Reference for last line syntax - http://www.w3schools.com/cssref/tryit.asp?filename=trycss_js_background-image
EDIT: Its not working. No image is being put on the cube's face.
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('input');
var container = document.getElementById('image-block');
function onFilePicked(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(event) {
var image = event.target.result;
container.style.backgroundImage = 'url(' + image + ')';
};
reader.readAsDataURL(file);
}
input.addEventListener('change', onFilePicked);
});
#image-block {
width: 100px;
height: 100px;
}
<input type="file" id="input">
<div id="image-block"></div>
my code looks like this;
<form>
<input type="text" />
<input type="file">
</form>
<div id="notes"></div>
i got the text variables to work, however, i cannot get this silly image thing to work, i've looked at loads of tutorials but i simply cannot manage to do it
i know i have to do something with
(document.getElementById("file").files)[0] != null) {
var pic = (document.getElementById("file").files)[0];
var imgUrl;
var reader = new FileReader();
reader.onload = function(e) {
var imgURL = reader.result;
saveDataToLocalStorage(imgURL);
reader.readAsDataURL(pic);
for the image and then use the JSON.parse to get the url back and show it on the page
but i cannot figure out how it works, neither can i find any examples that aren't too complicated to implement it into my own code
in this fiddle i have provided all the code that i have at the moment
http://jsfiddle.net/VXdkC/
i really hope you guys can help me out, i've been messing around with this thing the past 2 days and it's starting to frustrate me :(
Here's how I'd do it :
var notes = localStorage.getItem('notes'),
arr = [];
if (notes) {
arr = JSON.parse(notes);
$.each(arr, function(k,v) {
console.log(v)
var h1 = $('<h1 />', {text: v.title});
var p = $('<p />', {text: v.msg});
var img = $('<img />', {src: v.image});
$('#notes').append(h1, p, img);
});
}
$('#clear').click(function () {
if (confirm('This will clear all notes, are you sure?')) {
window.localStorage.setItem('notes','');
location.reload();
}
return false;
});
$('#addNote').click(function () {
var Title = $('#title').val();
var Message = $('#message').val();
var file = $('#file').prop('files')[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
var b64 = e.target.result;
var note = {
image : b64,
title : Title,
msg : Message
}
arr.push(note);
localStorage.setItem('notes', JSON.stringify( arr ));
$('#notes').prepend("<div class='entry'><h1>" + Title + "</h1></p>" + "<p>" + Message + "<img src=" + b64 + " /></p> </div>");
}
return false;
});
FIDDLE
Its pretty simple
var pic = document.getElementById("file").files[0];
var imgUrl;
var reader = new FileReader();
reader.onload = function(e) {
var imgURL = reader.result;
$('#notes').prepend("<div class='entry'><h1>" + Title + "</h1></p>" + "<p>" + Message + "<img src=" + imgURL + "></p> </div>");
var notes = $('#notes').html();
localStorage.setItem('notes', notes);
saveDataToLocalStorage(imgURL);
}
reader.readAsDataURL(pic);
http://jsfiddle.net/VXdkC/2/
Live demo here (click).
the html:
<input id="file" type="file">
the js:
var fileInput = document.getElementById('file');
fileInput.addEventListener('change', function(e) {
var reader = new FileReader(); //create reader
reader.onload = function() { //attach onload
//do something with the result
console.log(reader.result);
localStorage.img = reader.result; //saved to localStorage
createImg(localStorage.img); //retrieved from localStorage
};
var file = e.target.files[0];
reader.readAsDataURL(file); //trigger onload function
});
function createImg(dataUri) {
var img = document.createElement('img');
img.src = dataUri;
document.body.appendChild(img);
}