remove or close specific images in a multi uploaded images functionality - javascript

Here I have multi uploading image functionality.
So here if the user selects Multiple images so using the below JavaScript code we can upload multiple images.
But here I want to enhance the functionality and the uploaded images should have a cross icon like close the image if the user doesn't want to upload the specific image he will be able to delete or remove the desired image, not all the image which image is not the good user can able to remove that image.
<input id="files" type="file" name="filename" accept="image/*" multiple>
<div id="preview"><span id="cross">×</span>
</div>
const prev = (file) => {
const fr = new FileReader();
fr.onload = () => {
const img = document.createElement("img");
img.src = fr.result;
document.querySelector('#preview').append(img);
};
fr.readAsDataURL(file);
};
const files = document.querySelector("#files");
files.addEventListener("change", (a) => {
if (!a.target.files) return;
[...a.target.files].forEach(prev);
});

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>

jQuery multiple image preview with file name, file size and delete function for each image

I'm using this awesome tutorial to preview multiple image before upload.
Now I need to put some information, file name & file size.
Below is the sample:
And the JS:
function previewImages()
{
var preview = document.querySelector('.gallery');
if(this.files)
{
[].forEach.call(this.files, readAndPreview);
}
function readAndPreview(file)
{
if (!/\.(jpe?g|png|gif)$/i.test(file.name))
{
return alert(file.name + " is not an image");
}
var reader = new FileReader();
reader.addEventListener("load", function() {
var image = new Image();
image.width = 150;
image.height = 150;
image.title = file.name;
image.src = this.result;
preview.appendChild(image);
});
reader.readAsDataURL(file);
}
}
document.querySelector('#uploadFile').addEventListener("change", previewImages);
HTML:
<span class="btn btn-default btn-file">
Browse <input type="file" name="uploadFile" id="uploadFile" multiple="multiple"/>
</span>
<div class="gallery" style="display: flex; flex-wrap: wrap;"></div>
I know to get the file size and file name is using this: file.size & file.name.
But now how to put that information on my code?
And 1 more how to add delete button for each image and function to delete it?
I made some suggestions in a comment, but perhaps they weren't helpful. Here's a more complete answer.
Here's a simplified JSFiddle which adds some text under the image. I've just faked a placeholder image to simplify things and focus on the question you asked.
You really only need to do a few things:
1) Create an HTML element to hold your new text. If you don't add this, it won't style well under the <img>. You could add an empty container inside your gallery for text, but going by the name "gallery", it is intended for multiple pictures, so it doesn't make sense to add a bunch of empty placeholders.
You can create an element with (you could use any element of course):
var info = document.createElement("div");
2) Add text to that element. You can do that in several ways, maybe best is:
var text = document.createTextNode('your text');
info.appendChild(text)
3) Add your new element to the DOM, specifically after your new image:
preview.appendChild(info);
Putting it all together (JSFiddle), with some simplification:
var preview = document.querySelector('.gallery'),
image = new Image(),
info = document.createElement("div");
image.width = 150;
image.height = 150;
image.title = 'Foo Title';
image.src = 'https://via.placeholder.com/150';
info.appendChild(document.createTextNode(image.title));
info.appendChild(document.createElement("br"));
info.appendChild(document.createTextNode(image.width + ' x ' + image.height + 'px'));
preview.appendChild(image);
preview.appendChild(info);

Save picture to local dir with Ionic

I'm looking forward to save/upload picture in a local directory in Windows using IONIC 3 / Cordova. Indeed, the user has to choose a file (jpg) from a folder, and I want to copy this file in another directory.
I tried with this.file.copyFile(path, name, newPath, newName) but it doesn't work and I don't understand why. I also tried with file-transfer plugin (https://ionicframework.com/docs/native/file-transfer/), but it seems I have to get an endpoint in an API to upload the file.
Please find below the function I use to copy the file when the user clicks on a submit button:
private copyFileToLocalDirBrowser(namePath, currentName, newFileName) {
this.file.copyFile(namePath, currentName, "file:///C://Users//myName//Desktop//imgs//", newFileName).then(success => {
console.log("Picture imported!");
}, error => {
this.presentToast("Error:" + error);
});
}
In the constructor, I declared private file: File and the import is import { File } from '#ionic-native/file';.
The user clicks on an input node (type file), to choose the file he/she wants :
<input name="pictureID" id="inputFile" type="file" (change)="showThumb($event)"/>
And here the showThumb function:
var files = e.target.files;
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) {
//Getting URI :
if (e.target.result) {
this.imageURI = e.target.result;
// Render thumbnail.
var img = document.createElement("img");
img.setAttribute('src', this.imageURI);
img.setAttribute('title', theFile.name);
img.setAttribute('id', "thumb");
document.getElementById('thumb-for-browser').appendChild(img);
}
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
Then, when the user clicks on a "Submit" button, I want to save the picture that I displayed a thumb on a local directory "file:///C://Users//myName//Desktop//imgs//".
Thanks in advance for your help.
Kind regards,

Upload image with a single button in html

I'm a newbie in html/javascript and made two buttons that can upload image (choose file button and upload button).
However, I want to make it to just a single button and don't know how to combine those two button. I already searched on google, they said we can use onchange to combine submit button but I already have onchange function that can show image right away after choosing image file to iframe.
Here is my html code for <form>
<form action="/upload", method="post", enctype="multipart/form-data">
<div style='height:0px; width:0px; overflow:hidden;'><input type="file" name="upFile" id="upFile" onchange="getCmaFileView(this, 'name').submit()" target="dropzone_1"/></div>
</form>
Also, here is my script and button
<script type = "text/javascript">
function getFile(){
document.getElementById("upFile").click();
}
</script>
...
<li><a onclick="getFile()" style="cursor:pointer; color:#000000;">Choose File</a></li>
I tried with adding .submit() in onchange, but it didn't work.
Does anybody have an idea for this?
Please please help me out here!
Thanks in advance.
EDIT
function getCmaFileInfo(obj,stype) {
var fileObj, pathHeader , pathMiddle, pathEnd, allFilename, fileName, extName;
var file;
var img, reader;
// file = upload.files[0];
upload = document.getElementsByTagName('input')[0];
holder = document.getElementById('dropzone');
reader = new FileReader();
file = upload.files[0];
var iupload, holder;
reader.onload = function (event) {
img = new Image();
//console.log(event.target.result);
img.src = event.target.result;
img.width = document.getElementById("dropzone").clientWidth;
img.height= window.innerHeight;
// note: no onload required since we've got the dataurl...I think! :)
holder.innerHTML = '';
holder.appendChild(img);
};
reader.readAsDataURL(file);
}
function getCmaFileView(obj,stype) {
getCmaFileInfo(obj,stype);
}
Can't you just add one more function/code in your getCmaFileView() - Which will just submit the form? Also it will be called after your image viewing part is done so that may solve your problem.
function getCmaFileView(obj,stype) {
getCmaFileInfo(obj,stype);
//form.submit() OR call_to_your_submit_function();
}

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

Categories

Resources