Preview last uploaded image - javascript

I'm using an old project where I could upload many images but for this one, I only need just one. When uploaded, I should see what's uploaded (preview). When first uploaded, I see the image. If uploaded a different image, I still see the first image. I dont want that, I need to preview the last uploaded image.
JavaScript:
$('.receipt.upload').on('change', function(e) {
let id = e.target.id;
let files = e.target.files;
let image = files[0];
let reader = new FileReader();
reader.onload = function(file) {
let img = new Image();
console.log(file);
img.src = file.target.result;
$('.'+id).replaceWith(img);
}
reader.readAsDataURL(image);
//console.log(files);
});
Rails html.erb:
<div>
<%= image_tag('/assets/receipt/missing-receipt.jpg', class: "receipt#{contract.id}") %>
</div>
// Inside a form
<div>
<%= f.file_field :receipt, id: "receipt#{contract.id}" , class: "receipt upload"%>
</div>
Change these makes no difference:
let files = e.target.files[0];
let image = files;

Created <img> img does not have .className set to <input type="file"> .id. At second change event no element exists in document with id at jQuery() call $('.'+id).
Set the .className of replacement element img to id.
$('.receipt.upload').on('change', function(e) {
let id = e.target.id;
let files = e.target.files;
let image = files[0];
let reader = new FileReader();
reader.onload = function(file) {
let img = new Image();
img.className = id; // set `img` `.className` to `id`
console.log(file);
img.src = file.target.result;
$('.'+id).replaceWith(img);
}
reader.readAsDataURL(image);
});

You don't need the FileReader...
$('.receipt.upload').on('change', function(e) {
let {id, files} = this
let img = new Image
img.src = URL.createObjectURL(files[0])
img.className = id
$('.'+id).replaceWith(img)
})

Related

How to convert reader.readAsDataURL(file) to readAsArrayBuffer

I have a component which allows me to drag multiple images onto the page and display the preview of those images. The following code achieves that:
displayPreviews(files: FileList) {
for (let i = 0; i < files.length; i++) {
const file = files.item(i);
const reader = new FileReader();
reader.onload = () => {
const image = reader.result as string;
this.uploadFileArray.push({
id: 'id',
image: image,
});
};
reader.readAsDataURL(file);
}
}
----------
<li *ngFor="let image of uploadFileArray">
<div *ngIf="image && image !== ''" [ngStyle]="{'background-image': 'url(' + image.image + ')'}"></div>
</li>
However, when selecting a large amount of images, it slows down the interaction with the rest of the page (form filling etc). I read that reader.readAsArrayBuffer can help alleviate that issue. However, I don't know how to integrate it. The below shows a grey box as it's no longer reading the image in the preview.
detectPhotos(files: FileList) {
for (let i = 0; i < files.length; i++) {
// Reference to a file
const file = files.item(i);
const reader = new FileReader();
reader.onload = () => {
const image = reader.result;
this.uploadFileArray.push({
id: 'id',
image: image,
});
};
reader.readAsArrayBuffer(file);
};
}
One issue of using readAsDataURL, the browser is going to have to convert blob to dataURI and then to display it, it's having to decode the dataURI. If you don't need to process the images first etc, you can use URL.createObjectURL to create a URL that references the BLOB instead.
Be aware, that URL.createObjectURL will keep the blob in memory until you call URL.revokeObjectURL(), it won't get GC'ed until you do. If using something like React, you could attach this to a useEffect dismount, if using pure JS you will want to keep a reference of these to clear when your done.
document.querySelector('input').addEventListener('change', function (e) {
for (const file of e.target.files) {
const url = URL.createObjectURL(file);
const img = document.createElement('img');
img.style.width = "100px";
img.setAttribute('src', url);
img.onload = () => {
URL.revokeObjectURL(url);
};
document.querySelector('#images').appendChild(img);
}
});
<input type="file" name="files" multiple accept="image/*"/>
<div id="images"></div>

Unable to select files on Mobile both IOS and Android

I'm trying to be able to upload an image to change a background of a table automatically, but it is only working on Desktop computers, it won’t work on neither IOS nor Android, anyone has any pointers? Thanks in advance.
const frame = document.getElementById('table');
const file = document.getElementById('file');
const reader = new FileReader();
reader.addEventListener("load", function () {
frame.style.backgroundImage = `url(${ reader.result })`;
}, false);
file.addEventListener('change',function() {
const image = this.files[0];
if(image) reader.readAsDataURL(image);
}, false)
Try using object urls
document.body.id = 'table'
const [{style}, file] = document.querySelectorAll('#table, #file')
file.addEventListener('change', img => {
[img] = file.files
style.backgroundImage = img ? `url(${URL.createObjectURL(img)})` : ''
})
<input type=file id=file accept="image/*">

How to display paragraphs and images from div in order?

I am building a small web-tool where editors can write content by using buttons to add paragraphs and images. I store the elements with an id ((number of element) starting at 0 and incremented for every new element) and load with a button in order to a div "preview" where the content is supposed to be displayed as in the web page later on.
My issue is that, for a reason I don't understand, the image is always displayed below all the paragraphs instead of being in order. Presumably there is an easy fix, but I am very new to HTML, CSS and JS and couldn't find the solution online.
Sorry if this is a stupid mistake or the solution was already posted somewhere.
Javascript handling the preview rendering:
// Preview current document status
document.getElementById("previewButton").addEventListener("click", function() {
// Clear
document.getElementById("preview").innerHTML = "";
// Add all elements properly
var section = document.getElementById("preview");
var id = "preview";
for (var counter = 0; counter < element_counter; counter++) {
var type = document.getElementById(counter).nodeName;
// If text element
if (type === "TEXTAREA") {
var paragraph = document.createElement("p");
var text = document.getElementById(counter).value;
paragraph.setAttribute("id", id + counter);
paragraph.setAttribute("class", "flow-text");
paragraph.append(text);
section.appendChild(paragraph);
}
// If image element
if (type === "INPUT") {
var file = document.getElementById(counter).files[0];
var reader = new FileReader();
reader.onload = function(e) {
var image = document.createElement("img");
image.setAttribute("id", id + counter);
image.setAttribute("src", e.target.result);
image.setAttribute("class", "materialboxed responsive-img");
section.appendChild(image);
}
reader.readAsDataURL(file);
}
}
});
This might work. I can't test though without your code. However basically the principle at work is to isolate some of the vars so they represent distinct instantiations. And then immediately add the image element to the DOM. The reader.onload is expected to run asynchronously still.
enter code here if (type === "INPUT") {
(function() {
var file = document.getElementById(counter).files[0];
var reader = new FileReader();
var image = document.createElement("img");
image.setAttribute("id", id + counter);
image.setAttribute("class", "materialboxed responsive-img");
section.appendChild(image);
reader.onload = function(e) {
image.setAttribute("src", e.target.result);
}
reader.readAsDataURL(file);
}());
}

Javascript image upload and display

My basic task is select image and display it,without saving it in database.
For this
1.I have made a select tag in html,through which I can upload the image.
2.I have made a blank image tag in which at there is no image source,alternate is upload image.
3.select tag has onchange javascript event handler which calls javascript function changeimage.
<script>
function changeimage()
{
document.form_name.imagetag.src=document.form_name.filetag.value;
}
</script>
In above Code
form_name : Is the name of my form
<form name = "form_name">
imagetag : Is the name of my Img tag
<Img src=" " name = "imagetag">
filetag : Is the name of my
<input type="file" name = "filetag" onchange="changeimage()">
I have save file using php extension.And when I try to print the value of filetag it shows "C:\fakepath\image.png",display this address for all image.
I have save my php file in www location.
I am using window 7,wamp server and chrome latest version.
You may want to checkout this solution (where my code derives from). It involves a little bit of jQuery but if you truly must write it out in pure JS, here you go.
Note: I modified your tags to conform to the JS below. Also try to stay away from writing any inline scripts. Always good to keep your HTML and JS loosely coupled.
var fileTag = document.getElementById("filetag"),
preview = document.getElementById("preview");
fileTag.addEventListener("change", function() {
changeImage(this);
});
function changeImage(input) {
var reader;
if (input.files && input.files[0]) {
reader = new FileReader();
reader.onload = function(e) {
preview.setAttribute('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
<input type="file" id="filetag">
<img src="" id="preview">
You can also use the Image() constructor. It creates a new HTML Image Element.
Example -
document.getElementById("filetag").addEventListener("change", function(e) {
let newImg = new Image(width, height);
// Equivalent to above -> let newImg = document.createElement("img");
newImg.src = e.target.files[0];
newImg.src = URL.createObjectURL(e.target.files[0]);
output.appendChild(newImg);
});
Reference - https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
You need one input tag to upload file and a image tag to render on the site.
The HTML and Javascript should look like
const renderFile = () => {
const render = document.querySelector('img')
const file = document.querySelector('input[type=file]').files[0]
const reader = new FileReader();
reader.addEventListener('load' , ()=> {
render.src = reader.result;
}, false)
if(file){
reader.readAsDataURL(file);
}
}
<input type = 'file' onchange = 'renderFile()' >
<br>
<br>
<img src = "" alt='rendered image' id='rendered-image' >
Simply on every upload the web page will show the image uploaded
You can Style the height and width of the image according to the need

JavaScript method that preloads image before displaying it doesn't work

Within an object constructor there's a method named addToViewport(), which has the role of simply displaying an image after preloading it:
window.onload = function(){
function ViewportObject(){
this.src = "https://chart.googleapis.com/chart?cht=qr&chs=500x500&chl=asdasdasd&choe=UTF-8&chld=L|0";
this.addToViewport = function(){
// Determine the DOM object type to create
var DOM_elem = "img",
obj = $(document.createElement(DOM_elem)),
img = new Object();
obj.addClass("object");
obj.css({"z-index":"100","width":"300px","height":"auto"});
// Preload the image before rendering it and computing its size
img.src = this.src;
img.onload = function(){
obj.attr("src",this.src);
obj.appendTo("body");
}
}
}
var o = new ViewportObject();
o.addToViewport();
}
The problem I've come across is that the script doesn't enter the "onload" event handler block, so the image doesn't get displayed.
I put together a web page with the same script as above on http://picselbocs.com/test/ for you to check out live.
What is it that I'm doing wrong here?
Try this:
change this
img = new Object();
....
img.src = this.src;
img.onload = function(){
obj.attr("src",this.src);
obj.appendTo("body");
}
to
img = new Image();
....
img.onload = function(){
obj.attr("src",this.src);
obj.appendTo("body");
}
img.src = this.src;

Categories

Resources