How to change image preview on button click - javascript

I have these codes to display the names of the files selected from input and it will preview the FIRST image:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var filename = input.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var files = $('#my_file')[0].files;
for (var i = 0; i < files.length; i++) {
$("#files").append('<div class="filename"><span name="fileNameList">'+files[i].name+'</span></div>');
}
$("#nextBtn").on("click",function(){
})
$('#myImg').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
What i want to do is that when i click on the "next" button,it will go to the next image selected or if i click on the "prev" button,it will go to the previous image(the last image if im displaying the first one).How do i go about doing this?Thank You.
UPDATE:
var fileInput = document.getElementById("my_file");
$(fileInput).on("change",function(event){
var next = document.getElementById("nextBtn");
next.onclick = function(xFlip){
curImage = curImage+xFlip;
var files = event.target.files;
if(curImage > files.length){
curImage = 1;
}
if(curImage == 0){
curImage = files.length;
}
$("#myImg").attr('src',files[curImage-1]);
};
console.log(document.getElementById("myImg").getAttribute("src"));
});
I did it this way as the images are retrieved from input type file multiple.
https://jsfiddle.net/bfr6wp7e/2/

Thanks for the challenge, it was my first meeting with the File API :)
Here is the jsFiddle with what I believe is the correct answer to your question:
https://jsfiddle.net/mkbctrll/aq9Laaew/300936/
JS part
const fileInupt = document.getElementById('fileInput')
const fileList = document.getElementById('fileList')
const slickSettings = {
infinite: true,
speed: 300,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true
}
const initSlickCarousel = (target, settings) => {
$(target).slick(settings);
}
const handleInputChange = (event) => {
console.log('We are handling it sir!')
const filesArray = Array.from(event.target.files)
filesArray.map((singleFile) => {
const outputImg = document.createElement('img')
const fileReader = new FileReader()
outputImg.className = 'img-thumbnail'
// Let's read it as data url - onload won't return a thing without it
fileReader.readAsDataURL(singleFile)
fileReader.onload = (event) => { outputImg.src = event.target.result }
console.log(outputImg)
fileList.appendChild(outputImg)
})
initSlickCarousel(fileList, slickSettings)
}
if(window.File && window.FileReader && window.FileList) { // check if browser can handle this
console.log('We are good to go sir!')
fileInput.addEventListener('change', handleInputChange, false)
} else {
alert('File features are not fully supported. Please consider changing the browser (newest Chrome or Mozilla).')
}
Though it won't be possible for me to get a grasp on that tech if not for the following sources:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
https://developer.mozilla.org/en-US/docs/Web/API/FileReader/onload

Sample code for Prev and Next image slide.
var numImages = 4;
var curImage = 1;
var imgArray =[
"one.jpg",
"two.jpg",
"three.jpg",
"four.jpg"
];
function imageShow( xflip ) {
curImage = curImage + xflip;
if (curImage > numImages)
{ curImage = 1 ; }
if (curImage == 0)
{ curImage = numImages ; }
document.images[2].src = imgArray[curImage - 1];
}
HTML buttons:
<input type="button" value="<< Prev" onclick="imageShow(-1)">
<input type="button" value="Next >>" onclick="imageShow(1)">

Related

How to change the image using javascript

const image_click = document.querySelectorAll('.imgClickBtn');
for (let image_clickBtn of image_click) {
image_clickBtn.addEventListener('click', (e) => {
let parent = image_clickBtn.parentElement;
let file = parent.querySelector('.updateprofile');
let filevalue = "";
file.click();
$('input[type="file"]').change(function(e) {
var fileName = e.target.files[0].name;
filevalue = fileName;
});
image_clickBtn.src = "assets/Blog-post/" + filevalue;
})
}
let imgdisplay;
const ImgBtnX = document.querySelectorAll('.ImgBtnX');
for (let ImgBtnX1 of ImgBtnX) {
ImgBtnX1.addEventListener("click",function () {
let parent = ImgBtnX1.parentElement;
let file = parent.querySelector('.Update_Post');
file.click();
window.imgdisplay = parent.querySelector('.Image_Blog');
})
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
window.imgdisplay.src = e.target.result;
}
reader.readAsDataURL(input.files[0]); // convert to base64 string
}
}
$('.Update_Post').change(function(e) {
readURL(this)
});
I've already solve my problem using this codes

file hex value checking not working

i am checking mime type validation using magic number hex value of a file type but its not working its not able to check and returning wrong alert message even if the file have right hex value as header.
Below is the details in code:
jQuery(document).ready(function() {
jQuery.fn.hasMimetype = function(ctrl) {
try {
ctrl.value = null;
} catch(ex) { }
if (ctrl.value) {
ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
}
}
const fileSelector2 = document.getElementById('file')
jQuery('#file').change(function(event) {
const file = event.target.files[0]
//alert(file.type);
const filereader = new FileReader()
filereader.onloadend = function(evt) {
var header2 = "";
var arr = (new Uint8Array(evt.target.result)).subarray(0, 4);
for(var i = 0; i < arr.length; i++) {
header2 += arr[i].toString(16);
}
if(header2 !=='d0cf11e0' || header2 !=='504b34'){
alert(header2);
alert("only doc/docx files are supported");
$('#file').hasMimetype(fileSelector2);
}
}
filereader.readAsArrayBuffer(file);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
This will always be true, regardless of the value of header2:
if(header2 !=='d0cf11e0' || header2 !=='504b34')
You probably want this instead:
if(header2 !=='d0cf11e0' && header2 !=='504b34')

Check selected image dimenions and alert if out of scope

I have a function that displays a selected image along with the image width and height. I would like to put in a check to alert if the image dimensions are greater that 390x390. I have marked the place I think a size check should go, I may be wrong. But it does not work anyway.
If someone has time you they please take a look to see how I should be dong the size check.
Many thanks in advance for your time.
My script:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("image_field"),
elPreview = document.getElementById("preview2"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
function readImage (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.addEventListener("load", function () {
var imageInfo = '<br><br>Your selected file size is<br> Display width ' +
image.width + ', Display height ' +
image.height + ' ' + '';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file);
}
});
reader.readAsDataURL(file);
}
elBrowse.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
// SOMETHING LIKE THIS
if( (image.width < 390 && image.height < 390) .test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Selected image is to small\n";
}
// END
}
}
if (errors) {
alert(errors);
}
});
so you need to move the checking to the event listener because that's the first place where you can know the image resolution
here you don't have the errors list, so you need to modify it a bit yet, but you can start from here:
window.URL = window.URL || window.webkitURL;
var elBrowse = document.getElementById("image_field"),
elPreview = document.getElementById("preview2"),
useBlob = false && window.URL; // `true` to use Blob instead of Data-URL
function readImage (file) {
var reader = new FileReader();
reader.addEventListener("load", function () {
var image = new Image();
image.addEventListener("load", function () {
if(image.width <= 390 && image.height <= 390)
{
var imageInfo = '<br><br>Your selected file size is<br> Display width ' +
image.width + ', Display height ' +
image.height + ' ' + '';
elPreview.appendChild( this );
elPreview.insertAdjacentHTML("beforeend", imageInfo +'<br>');
} else {
alert ( file.name +" Selected image is to big\n");
}
});
image.src = useBlob ? window.URL.createObjectURL(file) : reader.result;
if (useBlob) {
window.URL.revokeObjectURL(file);
}
});
reader.readAsDataURL(file);
}
elPreview.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
readImage( file );
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
if (errors) {
alert(errors);
}
});
for the file variable (on the first place you aimed to check the dimensions, you can only base your condition on the file size - in bytes)
I'm not sure if I understood the question, but did you mean something like this?
elBrowse.addEventListener("change", function() {
var files = this.files;
var errors = "";
if (!files) {
errors += "File upload not supported by your browser.";
}
if (files && files[0]) {
for(var i=0; i<files.length; i++) {
var file = files[i];
if ( (/\.(png|jpeg|jpg|gif)$/i).test(file.name) ) {
if(image.width <= 390 && image.height <= 390)
{
readImage( file );
} else {
errors += file.name +" Selected image is to big\n";
}
} else {
errors += file.name +" Unsupported Image extension\n";
}
}
}
if (errors) {
alert(errors);
}
});
Loading the image and getting the dimension is async, so you can't use the check inside the for loop, it has do be done inside the callback
(unless you are using async/await or generators+yield)
var elBrowse = document.getElementById('image_field')
var elPreview = document.getElementById('preview2')
// No point in addthing the listener if we can't read them anyway
if ('files' in elBrowse) {
// No need for addEventListener if you only going to have 1 listener
elBrowse.onchange = () => {
for (let file of elBrowse.files) {
file.image().then(image => {
// Now if you don't like the extension you can always transform it
// using the canvas element...
if (image.width < 390 && image.height < 390)
return console.error(file.name + ' is to small\n')
let info = `<br><br>${file.name} size is ${file.size} bytes
and dimension is ${image.width}x${image.height}<br>`
elPreview.appendChild(image)
elPreview.insertAdjacentHTML('beforeend', info)
}, err => {
console.error(file.name + " Isn't an image")
})
}
}
} else {
console.info('reading the file is not possible, use flash alternetive?')
}
<!--
Getting a bit of help from Screw-FileReader
ref: https://github.com/jimmywarting/Screw-FileReader
-->
<script src="https://cdn.rawgit.com/jimmywarting/Screw-FileReader/master/index.js"></script>
<!--
use the accept attribute to say that you only want images
So you don't have to check for it in your code
But for just in case we listen for image.onerror when we load the image
-->
<input id=image_field type=file multiple accept="image/*">
<div id=preview2>

Preview images before upload

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">

Send default image with ajax

Hi guys how can i convert a image to object in this code for example:
var img = $('<img id="dynamic">');
img.attr('src', 'http://macreationdentreprise.fr/wp-content/uploads/2012/06/ouvrir-un-restaurant.jpeg');
var obj=img.ConvertToObject();
// so i can now use obj.filename; and obj.data;
The reason to do that is if i wan't to upload this image automatically if the input file isn't set:
<input id="picture_zone_upload_input_ID" type="file" name="picture_zone_upload_input" class="picture_zone_upload_input" multiple title="Choose a file to upload"/>
EDIT
function configure_zone_upload() {
$("#picture_zone_upload_input_ID").change(function (event) {
$.each(event.target.files, function (index, file) {
var reader = new FileReader();
reader.onload = function (event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
//alert("index: " + index);
upload_img_count++;
configure_upload_img(object.data, upload_img_count);
files.push(object);
};
reader.readAsDataURL(file);
});
var files = event.target.files;
for (var x = 0; x < files.length; x++) {
data.append(x, files[x]);
}
//alert(files.length);
AJAX_upload_Profile(data, upload_img_count);
});
}
If there isn't a input file how can i set the my default image to send it with ajax ??
EDIT2
If event.target.files; is null how can i set file from new image:
var files = event.target.files;
for (var x = 0; x < files.length; x++) {
data.append(x, files[x]);
}
//alert(files.length);
AJAX_upload_Profile(data, upload_img_count);
I guess you can do this:
object.filename = file.name || defaultImg;
where defaultImg is a variable which contains a default img with src.
somthing like:
reader.onload = function (event) {
object = {};
object.defaultImg = $('<img>',{"src" : "defaultImg/path/img.jpeg"}); // <--declare here
object.filename = file.name
object.data = event.target.result || object.defaultImg; //<---use it here;
//alert("index: " + index);
upload_img_count++;
configure_upload_img(object.data, upload_img_count);
files.push(object);
};

Categories