uploading multiple images and saving them to localStorage in javascript - javascript

I am trying to make a feature for my web application that allows the user to upload multiple images as a part of a blog post, then view them later on a page that shows a list of all blog posts. What I am trying to do is, allow the user to upload multiple images and save those images to localStorage. Currently I am looping through all the image files the user has uploaded, then adding a new fileReader to each one. In order to add them to the localStorage, I know I have to make the key value of each image different (i.e. img1=the first image, img2=the second image, etc.) As per the code below, I am changing the key value for each image uploaded using a for loop, and setting it to img${i}.
However when I try to add a "load" event listener onto each fileReader component to read each individual image file in order to save it onto localStorage, because it is a "load" event the value of the "i" is different. So as a result, I can only save the final image that has been uploaded (i.e. img3). I am assuming this is caused by the code that is within a "load" event so that it will only consider the final "i" value when all the files have loaded. Would there be a way around this issue? Any help towards the right direction is greatly appreciated. I am trying to achieve this in pure javascript so no jquery please. Thank you.
HTML
<!--Upload images-->
<input type="file" id="filetag" multiple accept=".jpg,.jpeg,.png,.gif">
<img id="preview">
Javascript
const fileSelector=document.getElementById('filetag');
const display = document.getElementById("preview");
fileSelector.addEventListener('change',(e)=>{
//gets all the files uploaded
let fileList = e.target.files;
console.log(fileList)
for(i=0;i<fileList.length;i++){
//add a new fileReader for each element
let reader = new FileReader();
reader.addEventListener("load", () =>{
//store each uploaded image into localStorage
localStorage.setItem(`img${i}`,reader.result)
console.log(i)
})
reader.readAsDataURL(fileList[i]);
}
})

First, I don't think that you should use LocalStorage for this. Besides LocalStorage size is limited. In case you have a back-end, those images should be saved in the server, and then just load them with the URL, like any normal website.
In any case, I answer your question. Instead of using an array (and having that problem with the index), turn it into an object and then use the object key:
let fileList = e.target.files;
let files = {};
let index = 0;
for(let file of files) {
files[index] = file;
index ++;
}
// Now iterate object instead of array
Object.keys(files).forEach( key => {
let reader = new FileReader();
reader.addEventListener("load", () =>{
localStorage.setItem(`img${key}`,reader.result)
})
reader.readAsDataURL(files[key]);
});

Related

Is there any way to make the edited image downloadable in javascript

Hi I am making a web app that takes a normal image and helps you to edit it.
> > This is the function for applying the filters on the user image.
function applyFilter() {
var computedFilters = "";
controls.forEach(function (item) {
computedFilters +=
item.getAttribute("data-filter") +
"(" +
item.value +
item.getAttribute("data-scale") +
") ";
});
image.style.filter = computedFilters;
downloadableImage.style.filter = computedFilters;
}
> > > Here I am adding the eventListener for showing the live editing image to the user.
userFile.addEventListener("change", function () {
const reader = new FileReader();
reader.addEventListener("load", () => {
localStorage.setItem("userImage", reader.result);
image.setAttribute("src", localStorage.getItem("userImage"));
downloadableImage.setAttribute("src", reader.result);
downloadLink.setAttribute("href", localStorage.getItem("userImage"));
});
reader.readAsDataURL(this.files[0]);
});
I want to make the image that is downloadable to be edited according to the user.
Just to download the image, you just need to add a download attribute to the download link.
In your case, do downloadLink.setAttribute("download", "download")
EDIT:
Well, I'm not exactly sure about how to do that in your case, but this link may help.
It explains blobs and object URLS, and what you would is:
create a blob and object URL for the image
give the download attribute to the downloadLink
specify the href attribute as the blob URL
and it works!
IMPORTANT
You should also read this mdn doc for more information about ObjectURLS.
Remember that you have to delete (revoke) each URL once an edit has been made and create a new ObjectURL:
Blobs are objects that are used to represent raw immutable data. Blob objects store information about the type and size of data they contain, making them very useful for storing and working file contents on the browser.
They are not changed(the raw, immutable data) and therefore should be deleted when you no longer need them:
Browsers will release object URLs automatically when the document is unloaded; however, for optimal performance and memory usage, if there are safe times when you can explicitly unload them, you should do so
See here and here for more info

in js, why is my filereader unable to track my inputfile when I edited it

Maybe naive question but I'm wondering this:
I have an html input allowing me to find a local file on my computer. <input type="file" id="importFile">
From this input, i create a FileReader in js to display the text file content on my page
var search_file = document.getElementById("search_file")
search_file.addEventListener('change', function(){
var reader = new FileReader();
var tmp = [];
reader.readAsText(file_to_survey);
reader.onload = function(e) {
var contents = e.target.result;
//function to edit html thanks to content//
}, false);
This part is actually working well BUT if I edit or replace the file I targeted (with exact same file name), I'm not able to display the file without to search it again with the html input mentionned above.
Is there a way to keep trace of my file even after edition?
Many thanks for your help. I dug quiet a lot to solve my problem but maybe I'm thinking the wrong way. Any clue would be nice.
Because that's how the input type=file element works, and to my best knowledge there is no way for you to force the browser to automatically re-read a file from the user's hard drive without their express consent.
You can put the change handler of the file input in a separate function, and call that function when needed.
function loadFile () {
var reader = new FileReader();
reader.addEventListener('load', function () {
file = reader.result;
// Handle the changes here
console.log(file);
});
reader.readAsText(fileField.files[0]);
}
const fileField = document.getElementById('load'),
reloadBut = document.getElementById('reload');
let file;
reloadBut.addEventListener('click', loadFile);
fileField.addEventListener('change', loadFile);
<input type="file" id="load">
<button id="reload">Load</button>
A separate button is used to reload the file in this snippet, but you can call loadFile where ever you need, ex. in an interval or from some event handler knowing the file was changed etc.
Note: This works in Chrome only, other browsers seem to lose the reference to the file browsed into file input when the file is changed. Also, the file must be properly closed after saving, before reloading.

Can files be updated and read using the JavaScript FileReader interface?

I am reading a local CSV file using a web UI, and the HTML5 FileReader interface to handle the local file stream. This works great.
However, sometimes I want the file being read to be updated continuously, after the initial load. I am having problems, and I think it might have something to do with the FileReader API. Specifically, after the initial file load, I maintain a reference to the file. Then, when I detect that the size of the file has increased, I slice off the new part of the file, and get a new Blob object. However, there appears to be no data in these new Blobs.
I am using PapaParse to handle the CSV parsing, though I don't think that is the source of the problem (though it may be).
The source code is too voluminous to post here, but here is some pseudocode:
var reader = new FileReader();
reader.onload = loadChunk;
var file = null;
function readLocalFile(event) {
file = event.target.files[0];
// code that divides file up into chunks.
// for each chunk:
readChunk(chunk);
}
function readChunk(chunk) {
reader.readAsText(chunk);
}
function loadChunk(event) {
return event.target.result;
}
// this is run when file size has increased
function readUpdatedFile(oldLength, newLength) {
var newData = file.slice(oldLength, newLength);
readChunk(newData);
}
The output of loadChunk when the file is first loading is a string, but after the file has been updated it is a blank string. I am not sure if the problem is with my slice method, or if there is something going on with FileReader that I am not aware of.
The spec for File objects shouldn't allow this: http://www.w3.org/TR/FileAPI/#file -- it's supposed to be like a snapshot.
The fact that you can detect that the size has changed is probably a shortcoming of an implementation.

How do I save and restore a File object in local storage

I have an HTML5/javscript app which uses
<input type="file" accept="image/*;capture=camera" onchange="gotPhoto(this)">
to capture a camera image. Because my app wants to be runnable offline, how do I save the File (https://developer.mozilla.org/en-US/docs/Web/API/File) object in local storage, such that it can be retrieved later for an ajax upload?
I'm grabbing the file object from the using ...
function gotPhoto(element) {
var file = element.files[0];
//I want to save 'file' to local storage here :-(
}
I can Stringify the object and save it, but when I restore it, it is no longer recognised as a File object, and thus can't be used to grab the file content.
I have a feeling it can't be done, but am open to suggestions.
FWIW My workaround is to read the file contents at store time and save the full contents to local storage. This works, but quickly consumes local storage since each file is a 1MB plus photograph.
You cannot serialize file API object.
Not that it helps with the specific problem, but ...
Although I haven't used this, if you look at the article it seems that there are ways (although not supported yet by most browsers) to store the offline image data to some files so as to restore them afterward when the user is online (and not to use localStorage)
Convert it to base64 and then save it.
function gotPhoto(element) {
var file = element.files[0];
var reader = new FileReader()
reader.onload = function(base64) {
localStorage["file"] = base64;
}
reader.readAsDataURL(file);
}
// Saved to localstorage
function getPhoto() {
var base64 = localStorage["file"];
var base64Parts = base64.split(",");
var fileFormat = base64Parts[0].split(";")[1];
var fileContent = base64Parts[1];
var file = new File([fileContent], "file name here", {type: fileFormat});
return file;
}
// Retreived file object
Here is a workaround that I got working with the code below. I'm aware with your edit you talked about localStorage but I wanted to share how I actually implemented that workaround. I like to put the functions on body so that even if the class is added afterwards via AJAX the "change" command will still trigger the event.
See my example here: http://jsfiddle.net/x11joex11/9g8NN/
If you run the JSFiddle example twice you will see it remembers the image.
My approach does use jQuery. This approach also demonstrates the image is actually there to prove it worked.
HTML:
<input class="classhere" type="file" name="logo" id="logo" />
<div class="imagearea"></div>
JS:
$(document).ready(function(){
//You might want to do if check to see if localstorage set for theImage here
var img = new Image();
img.src = localStorage.theImage;
$('.imagearea').html(img);
$("body").on("change",".classhere",function(){
//Equivalent of getElementById
var fileInput = $(this)[0];//returns a HTML DOM object by putting the [0] since it's really an associative array.
var file = fileInput.files[0]; //there is only '1' file since they are not multiple type.
var reader = new FileReader();
reader.onload = function(e) {
// Create a new image.
var img = new Image();
img.src = reader.result;
localStorage.theImage = reader.result; //stores the image to localStorage
$(".imagearea").html(img);
}
reader.readAsDataURL(file);//attempts to read the file in question.
});
});
This approach uses the HTML5 File System API's to read the image and put it into a new javascript img object. The key here is readAsDataURL. If you use chrome inspector you will notice the images are stored in base64 encoding.
The reader is Asynchronous, this is why it uses the callback function onload. So make sure any important code that requires the image is inside the onLoad or else you may get unexpected results.
You could use this lib:
https://github.com/carlo/jquery-base64
then do something similar to this:
//Set file
var baseFile = $.base64.encode(fileObject);
window.localStorage.setItem("file",basefile);
//get file
var outFile = window.localStorage.getItem("file");
an other solution would be using json (I prefer this method)
using: http://code.google.com/p/jquery-json/
//Set file
window.localStorage.setItem("file",$.toJSON(fileobject));
//get file
var outFile = $.evalJSON(window.localStorage.getItem("file"));
I don't think that there is a direct way to Stringify and then deserialize the string object into the object of your interest. But as a work around you can store the image paths in your local storage and load the images by retrieving the URL for the images. Advantages would be, you will never run out of storage space and you can store 1000 times more files there.. Saving an image or any other file as a string in local storage is never a wise decision..
create an object on the global scope
exp: var attmap = new Object();
after you are done with file selection, put your files in attmap variable as below,
attmap[file.name] = attachmentBody;
JSON.stringify(attmap)
Then you can send it to controller via input hidden or etc. and use it after deserializing.
(Map<String, String>)JSON.deserialize(attachments, Map<String,String>.class);
You can create your files with those values in a for loop or etc.
EncodingUtil.base64Decode(CurrentMapValue);
FYI:This solution will also cover multiple file selection
You could do something like this:
// fileObj = new File(); from file input
const buffer = Buffer.from(await new Response(fileObj).arrayBuffer());
const dataUrl = `data:${fileObj.type};base64,${buffer.toString("base64")}`;
localStorage.setItem('dataUrl', dataUrl);
then you can do:
document.getElementById('image').src = localStorage.getItem('dataUrl');

When using plupload HOWTO duplicate file object when selected & submit it separately for a related server-side processing

I am using plupload to let users upload images. But I also want to generate thumbnails for preview before they finally decide to keep it. I understand currently "Image preview" feature is not present in plupload. So to work around this I decided to submit a new form containing just one file for each image added, & let the server process it & return a thumbnail.
Now my question is how do I get the handle on the file object from the plupload so that I can create an "input" file field dynamically.
Currently I iterate over uploader.files & set input.name but I dont know how to set the input.value field, since I cant seem to get the complete file path of the file added.
I am up for any suggestions (in addition to replacing this approach completely), I just need thumbnail of the file selected for upload.
Maybe my answer is a bit late, but I searched today for a similar solution and came up with the following approach. It will only work with the HTML5 Runtime.
As there is no way to get the file objects from plupload, I changed the onchange event of the dynamically created input field and store the file objects for myself. This is done by binding to the PostInit-Event.
After that I can show the image to the user by using the FileReader API introduced with HTML 5. So there is no need to send the image to the server. See my FilesAdded Listener below.
// Currently added File Objects
var nativeFiles = {};
var uploader = new plupload.Uploader({
runtimes : 'html5,html4',
// Your settings...
});
uploader.bind('PostInit', function(up, params) {
// Initialize Preview.
if(uploader.runtime == "html5") {
var inputFile = document.getElementById(uploader.id + '_html5');
var oldFunction = inputFile.onchange;
inputFile.onchange = function() {
nativeFiles = this.files;
oldFunction.call(inputFile);
}
}
});
uploader.bind('FilesAdded', function(up, files) {
for (var i in files) {
// Your code...
// Load Preview
if(uploader.runtime == "html5") {
var fileObject = uploader.getFile(files[i].id);
var reader = new FileReader();
reader.onload = (function(file, id) {
return function(e) {
var span = document.getElementById('thumb_'+id);
span.innerHTML = "<img src='"+e.target.result+"'/>";
};
})(nativeFiles[i], files[i].id);
reader.readAsDataURL(nativeFiles[i]);
}
}
});

Categories