I was looking at the new HTML5 file API for showing a preview of an image to be uploaded. I googled for some code and almost every example had the same structure, almost the same code. I don't mind copying, particularly when it works, but I need to understand it. So I tried to understand the code but I am stuck with one area and need someone to explain that small part:
The code refers to a HTML form input field and when the file is selected shows the preview image in a img tag. Nothing fancy. Simple. Here it is after removing all the noise:
$('input[type=file]').change(function(e) {
var elem = $(this);
var file = e.target.files[0];
var reader = new FileReader();
//Part I could not understand starts here
reader.onload = (function(theFile) {
return function(e) {
var image_file = e.target.result
$('#img_id').attr('src',image_file);
};
})(file);
reader.readAsDataURL(file);
//Upto here
});
I think that reader.onload needs to be assigned a plain event handler, so I replaced the entire section marked above to:
reader.readAsDataURL(file);
reader.onload = function(e) {
var image_file = e.target.result;
//#img_id is the id of an img tag
$('#img_id').attr('src',image_file)
};
And it worked as I expected it to work.
QUESTION: What's the original code doing that the above simplified code is missing? I understand that it is a function expression returning a function and then calling it… but for what? There is just too much of the original code copied around under tutorials and what not on it but no good explanation. Please explain. Thanks
Sure.
The function-wrapped function, here serves the specific purpose of remembering which file it was you were looking at.
This might be less of a problem using your exact codebase, but if you had a multiple-upload widget, and you wanted to display a row of previews:
var my_files = [].slice.call(file_input.files),
file, reader,
i = 0, l = my_files.length;
for (; i < l; i += 1) {
file = my_files[i];
reader = new FileReader();
// always put the handler first (upside down), because this is async
// if written normally and the operation finishes first (ie:cached response)
// then handler never gets called
reader.onload = function (e) {
var blob_url = e.target.result,
img = new Image();
img.src = blob_url;
document.body.appendChild(img);
};
reader.readAsDataUrl(file);
}
That should all work fine. ...except...
And it's clean and readable.
The issue that was being resolved is simply this:
We're dealing with async-handlers, which means that the value of file isn't necessarily the same when the callback fires, as it was before...
There are a number of ways to potentially solve that.
Pretty much all of them that don't generate random ids/sequence-numbers/time-based hashes to check against on return, rely on closure.
And why would I want to create a whole management-system, when I could wrap it in a function and be done?
var save_file_reference_and_return_new_handler = function (given_file) {
return function (e) {
var blob_url = e.target.result,
file_name = given_file.name;
//...
};
};
So if you had that at the top of the function (above the loop), you could say:
reader = new FileReader();
reader.onload = save_file_reference_and_return_new_handler(file);
reader.readAsDataUrl(file);
And now it will work just fine.
Of course, JS people don't always feel compelled to write named functions, just to store one item in closure to remember later...
reader.onload = (function (current_file) {
return function (e) {
var blob_url = e.target.result,
file_name = current_file.name;
};
}(file));
Related
I am very new to this concept of async ,await ,promise ..paradigms ..Please help me
I have an input field like this
I have a global variable var base64.How to fill base64 global variable with base encoded value. Inside the function in addEventListener reader.result shows base encoded value.How Can i pass it to outside global variable.I tried a lot .. as it seems to be a async function ..the behavior seems to be quiet different and seems very difficult in catching up and also I am not getting the expected result
<input type="file" id="photo" accept="image/*" required #change="UploadPhoto()" />
The change function of UploadPhoto() is ..{This i got from mozilla}
function UploadPhoto() {
const file = document.querySelector('#photo').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
// convert image file to base64 string
console.log(reader.result);
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
Also I will be greatful if you can explain me the working of reader.addEventListener and reader.readAsDataURL(file); with the case of asynchronous behavioured ..I googled a lot but couldnt find an article with detailed explaination of these two functions.
Wanting a global (in this case) is a symptom of not having the tools you need to do without it.
If you really needed a global, you could get it this way...
let b64Encoded;
function UploadPhoto() {
const file = document.querySelector('#photo').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
// convert image file to base64 string
b64Encoded = btoa(reader.result);
}, false);
But, as you suppose, the modern way to do it is to use promises. This will make the code simpler to understand, and will prove an even better decision when you get to actually posting the encoded file...
First wrap the file reader in a promise. Here's a fine post on the subject, and here's the punchline (slightly modernized)
async function readAsDataURL(file) {
return new Promise((resolve, reject) => {
const fr = new FileReader();
fr.onerror = reject;
fr.onload = () => {
resolve(fr.result);
}
fr.readAsDataURL(file);
});
}
Use it like this:
// we don't need this anymore :-)
// let b64Encoded;
async function UploadPhoto() {
const file = document.querySelector('#photo').files[0];
const result = await readAsDataURL(file);
const b64Encoded = btoa(result); // stack var, as it should be!
// insert real (promise-based) network code here
return myNetworkLibrary.post(b64Encoded);
}
The addEventListener method on file reader is part of the old school async: It says: file reader is going to do i/o on a separate thread. It will you tell you when it's done (that's the "event" part) by calling a function you specify (that's the "listener" part), pass it a function to call (that's the "add" part).
I've got an event listener that fires normally in FireFox, but somehow doesn't in Webkit based browsers.
function ProfilePictureFeedback(fileInput, target) {
fileInput.addEventListener('input', function() {
var profilePictureData = fileInput.files[0];
var reader = new FileReader();
reader.readAsBinaryString(profilePictureData);
reader.addEventListener("load", function () {
var result = btoa(reader.result);
target.style.background = 'url(data:image/jpeg;base64,' + result + ')';
target.style.backgroundSize = 'cover';
});
});
}
I've looked around for possible duplicate answers, one stating something about e.preventDefault();, but I have no idea how that exactly ties in to my problem.
Edit: Forgot to mention that no error messages are shown in the console.
So on WinXP I have been having a hard time converting a PNG file to an ICO with canvas. I found this method encodeImage. I don't know if it works but it looks promising but I can't figure out how to feed the image I drew on a canvas into imgITools.decodeData.
What should I use for aImageStream and/or aMimeType?
imgTools.decodeImageData(aImageStream, aMimeType, imgContainer);
This is more of my code:
img['asdf'].file = new FileUtils.File(myPathHere);
let iconStream;
try {
let imgTools = Cc["#mozilla.org/image/tools;1"]
.createInstance(Ci.imgITools);
let imgContainer = { value: null };
imgTools.decodeImageData(aImageStream, aMimeType, imgContainer);
iconStream = imgTools.encodeImage(imgContainer.value,
"image/vnd.microsoft.icon",
"format=bmp;bpp=32");
} catch (e) {
alert('failure converting icon ' + e)
throw("processIcon - Failure converting icon (" + e + ")");
}
let outputStream = FileUtils.openSafeFileOutputStream(img['asdf'].file);
NetUtil.asyncCopy(iconStream, outStream, netutilCallback);
Since you're having a canvas already(?), it would be probably easier to use either on of the following canvas methods:
toDataURI/toDataURIHD
toBlob/toBlobHD
mozFetchAsStream
There is also the undocumented -moz-parse-options:, e.g -moz-parse-options:format=bmp;bpp=32. (ref-tests seem to depend on it, so it isn't going away anytime soon I'd think).
So, here is an example for loading stuff into an ArrayBuffer.
(canvas.toBlobHD || canvas.toBlob).call(canvas, function (b) {
var r = new FileReader();
r.onloadend = function () {
// r.result contains the ArrayBuffer.
};
r.readAsArrayBuffer(b);
}, "image/vnd.microsoft.icon", "-moz-parse-options:format=bmp;bpp=32");
Here is a more complete example fiddle creating a 256x256 BMP icon.
Since you likely want to feed that data into js-ctypes, having an ArrayBuffer is great because you can create pointers from it directly, or write it to a file using OS.File.
I'm simply trying to use FileReader to display image files, however when I try to use more than 1 image, I get the following "InvalidStateError: DOM Exception 11". In firefox, however, it works fine.
Here's my code
function addImages(images)
{
var reader=new FileReader()
reader.onload=function()
{
$("#images").append('<img src="'+this.result+'"/><br/>')
}
for(var count=0;count<images.length;count++)
{
reader.readAsDataURL(images[count])
}
}
function uploadImagesToBrowser(e)
{
addImages(e.target.files)
}
$("#imagefiles").on("change",uploadImagesToBrowser)
Unfortunately doesn't work. As mentioned by janje you will need to create a new FileReader per iteration. Also remember to create a closure when binding the event handler, due to the "creating functions in a loop" problem in JavaScript.
Eric Bidelman's post is a rather good source:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
You have to create a new FileReader (and a new variable to store it in) for every iteration using readAsDataURL.
I'm using FileReader API to read files on local.
<input type="file" id="filesx" name="filesx[]" onchange="readmultifiles(this.files)" multiple="" />
<script>
function readmultifiles(files) {
var ret = "";
var ul = document.querySelector("#bag>ul");
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
for (var i = 0; i < files.length; i++) //for multiple files
{
var f = files[i];
var name = files[i].name;
alert(name);
var reader = new FileReader();
reader.onload = function(e) {
// get file content
var text = e.target.result;
var li = document.createElement("li");
li.innerHTML = name + "____" + text;
ul.appendChild(li);
}
reader.readAsText(f,"UTF-8");
}
}
</script>
If input includes 2 files:
file1 ---- "content1"
file2 ---- "content2"
I get this output:
file2__content1
file2__content2
How to fix code to display:
file1__content1
file2__content2
The problem is you're running the loop now but the callbacks you are setting are getting run later (when the events fire). By the time they run, the loop is over and remains at whatever the last value was. So it will always show "file2" in your case for the name.
The solution is to put the file name inside a closure with the rest. One way to do this is create an immediately-invoked function expression (IIFE) and pass the file in as a parameter to that function:
for (var i = 0; i < files.length; i++) { //for multiple files
(function(file) {
var name = file.name;
var reader = new FileReader();
reader.onload = function(e) {
// get file content
var text = e.target.result;
var li = document.createElement("li");
li.innerHTML = name + "____" + text;
ul.appendChild(li);
}
reader.readAsText(file, "UTF-8");
})(files[i]);
}
Alternately, you can define a named function and call it as normal:
function setupReader(file) {
var name = file.name;
var reader = new FileReader();
reader.onload = function(e) {
// get file content
var text = e.target.result;
var li = document.createElement("li");
li.innerHTML = name + "____" + text;
ul.appendChild(li);
}
reader.readAsText(file, "UTF-8");
}
for (var i = 0; i < files.length; i++) {
setupReader(files[i]);
}
Instead of using var, use let as the declared variable only be used in one loop.
for (let i = 0; i < files.length; i++) //for multiple files
{
let f = files[i];
let name = files[i].name;
alert(name);
let reader = new FileReader();
reader.onload = function(e) {
// get file content
let text = e.target.result;
let li = document.createElement("li");
li.innerHTML = name + "____" + text;
ul.appendChild(li);
}
reader.readAsText(f,"UTF-8");
}
Edit: Just use let instead of var in the loop. That fixes the issue OP had (but was only introduced in 2015).
Old answer (An interesting workaround):
While it is not exactly robust or future-proof, it is worth mentioning that this can also be achieved by adding a property to the FileReader object:
var reader = new FileReader();
reader._NAME = files[i].name; // create _NAME property that contains filename.
Then access it through e within the onload callback function:
li.innerHTML = e.target._NAME + "____" + text;
Why this works:
Even though the reader variable is replaced multiple times during the loop like i, the new FileReader object is unique and remains in memory. It is accessible within the reader.onload function through the e argument. By storing additional data in the reader object, it is kept in memory and accessible through reader.onload via e.target event argument.
This explains why why your output is:
file2__content1file2__content2
and not:
file1__content1file2__content2
The content is displayed correctly because e.target.result is a property within the FileReader object itself. Had FileReader contained a filename property by default, it could have been used and this whole mess avoided entirely.
A word of caution
This is called extending host objects (if I understand the difference between native objects...). FileReader is the host object that is being extended in this situation. Many professional developers believe doing this is bad practice and/or evil. Collisions may occur if _NAME ever becomes used in the future. This functionality isn't documented in any specification so it could even break in the future, and it may not work in older browsers.
Personally, I have not encountered any issues by adding additional properties to host objects. Assuming the property name is unique enough, browsers don't disable it, and future browsers don't change these objects too much, it should work fine.
Here are some articles that explain this quite well:
http://kendsnyder.com/extending-host-objects-evil-extending-native-objects-not-evil-but-risky/
http://perfectionkills.com/whats-wrong-with-extending-the-dom/
And some article on the problem itself:
http://tobyho.com/2011/11/02/callbacks-in-loops/
You can make a promise/callback for reading the file in the loop.
Promise-
fileBase64(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
resolve(reader.result);
};
reader.onerror = function(error) {
reject(error);
};
});
}
I am calling this function on onClick
onClick = async () => {
for (var i = 0; i < this.state.company_bank_statement_array.length; i++) {
let file = document.getElementById(
this.state.company_bank_statement_array[i]
);
let fileData = await this.fileBase64(file.files[0]);
this.state.bankStatements.push({
data: fileData,
filename: file.files[0].name,
});
}
};
I had the same problem, solved it by using Array.from
let files = e.target.files || e.dataTransfer.files;
Array.from(files).forEach(file => {
// do whatever
})
I think the best way to solve this problem is by recursively call a function that reads the blob file. So in my case I solve the problem with the following snippet code, maybe is a little complicated but it works in any scenario that I tried.
Notice that, I didn't pass the array and index as arguments. You need to call them with the object they belong to.
//Initialize blobs
var foo = new Blob(["Lorem ipsum dolor sit amet, consectetur adipiscing elit."], {
type: 'text/plain'
});
var bar = new Blob(["Sed tristique ipsum vitae consequat aliquet"], {
type: 'text/plain'
});
//Initialize array and index
var arrayOfBlobs = [foo, bar];
var arrayIndex = 0;
function fileRead () {
var me = this;
if (this.arrayIndex < this.arrayOfBlobs.length) {
var reader = new FileReader();
function bindedOnload(event) {
console.log("bindedOnload called");
console.log("reader results: ", event.target.result);
this.arrayIndex++; //Incrument the index
this.fileRead(); //Recursive call
}
//By Binding the onload event to the local scope we
//can have access to all local vars and functions
reader.onload = bindedOnload.bind(me);
reader.readAsText(this.arrayOfBlobs[arrayIndex]);
} else {
//This will executed when finishing reading all files
console.log("Finished");
}
}
//Call the fileRead for the first time
fileRead();