1

I tried to upload Multiple files and wants to read the content of the file for encrypt the data. I can able to read the single file properly , but I can't do it while upload multiple files am getting error reader is busy. If I create new Filereader while onloadend it gives me null value of content.

React JS - sample code:

let reader = new FileReader();
class FilReaderComp extends Component {
constructor(props) {
super(props);
this.state = {

}}
upLoadFileFolderFunc(e){
e.preventDefault();
let fileitemsList = e.target.files;
for (let i = 0; i < fileitemsList.length; i++) {
  let fileitems = fileitemsList[i];
  reader.onloadend = this.handleFileRead;
  reader.readAsText(fileitems);
  }
}

handleFileRead = (e) => {
const content = reader.result; here am reading content of the file

//here doing my function after getting content
}
render(){
return(
<input  type="file" className="custom-file-input" style={{display:"hide"}}
            onChange={this.upLoadFileFolderFunc} multiple/>
);}

export default withRouter(FilReaderComp);

1 Answer 1

2

Try wrapping your onload function in another function and enclose the filereader in the loop. Here the closure gives you access to each file being processed in turn via the variable f:

function openFiles(evt){
    var files = evt.target.files;

    for (var i = 0, len = files.length; i < len; i++) {
        var file = files[i];

        var reader = new FileReader();

        reader.onload = (function(f) {
            return function(e) {
                // Here you can use `e.target.result` or `this.result`
                // and `f.name`.
            };
        })(file);

        reader.readAsText(file);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.