I use JS FileReader. I want to get result after file reading operation and work with this data. FileReader is asynchronous and I don't know when result is ready. How to get it done right?
$(document).ready(function(){ $('#file_input').on('change', function(e){ var res = readFile(this.files[0]); //my some manipulate with res $('#output_field').text(res); }); }); function readFile(file){ var reader = new FileReader(), result = 'empty'; reader.onload = function(e) { result = e.target.result; }; reader.readAsText(file); //waiting until result is empty? return result; }
http://jsfiddle.net/ub22m/4/
It's show "empty".
How to wait until "result" is empty? Another way?
The FileReader result property returns the file's contents. This property is only valid after the read operation is complete, and the format of the data depends on which of the methods was used to initiate the read operation.
The readAsText() method is used to read the contents of the specified Blob or File . When the read operation is complete, the readyState is changed to DONE , the loadend event is triggered, and the result property contains the contents of the file as a text string.
FileReader can only access the contents of files that the user has explicitly selected, either using an HTML <input type="file"> element or by drag and drop. It cannot be used to read a file by pathname from the user's file system. To read files on the client's file system by pathname, use the File System Access API.
The FileReader. onload property contains an event handler executed when the load event is fired, when content read with readAsArrayBuffer, readAsBinaryString, readAsDataURL or readAsText is available.
Reading happens asynchronously. You need to provide a custom onload
callback that defines what should happen when the read completes:
$(document).ready(function(){ $('#file_input').on('change', function(e){ readFile(this.files[0], function(e) { // use result in callback... $('#output_field').text(e.target.result); }); }); }); function readFile(file, onLoadCallback){ var reader = new FileReader(); reader.onload = onLoadCallback; reader.readAsText(file); }
(See the Fiddle.)
Note that readFile
does not return a value. Instead, it accepts a callback function, which will fire whenever the read is done. The $('#output_field').text
operation is moved into the callback function. This ensures that that operation will not run until the reader's onload
callback fires, when e.target.result
will be filled.
Programming with callbacks is a bit difficult to get right at first, but it is absolutely necessary for implementing advanced functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With