How to use FileReader with React? (getting a strange error) - reactjs

I have tried solutions from
How to use FileReader in React?
and gotten the same error as my code.
I'm trying to use the FileReader() in a react component.
class Home extends Component {
onChange(e) {
let files = e.target.files;
console.log(files);
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = e => {
console.log(e.target.result);
};
}
render() {
return (
<div onSubmit={this.onFormSubmit}>
<h1>Upload File Here</h1>
<input type="file" name="file" onChange={e => this.onChange(e)} />
</div>
export default Home;
console.log(files) returns the uploaded file (if I run it without the rest of the onChange() code). When I run the whole thing, I get an error message of:
Error: cannot read as File: {} on reader.readAsDataURL(files[0]);
I'm following this tutorial exactly and it is working fine for them. Any thoughts?!
https://www.youtube.com/watch?v=sp9r6hSWH_o&t=50s

Try this
Change
onChange(e) {
let files = e.target.files;
console.log(files);
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = e => {
console.log(e.target.result);
};
}
To
onChange = e => {
let files = e.target.files;
console.log(files);
let reader = new FileReader();
reader.onload = r => {
console.log(r.target.result);
};
reader.readAsDataURL(files[0]);
}

Related

How can I read from local file in angularjs without using directive?

I have input type="file" and I need to read the event.target.files.
I tried
<input type="file" ng-change="readFile($event)" />
readFile = (e) => {
const file = e.target.files[0];
console.log('file', file);
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = async (evt) => {
const xmlData: string = evt.target.result;
const annotManager = this.wvInstance.annotManager;
const ann = await annotManager.importAnnotations(xmlData);
};
reader.readAsText(file);
}
but in file I don't get File object instnace after the file is selected
I need to get something like this, but I don't get it with this example
How can I do this ?

How to read the content of the file using FleReader while upload multiple file upload in react js

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);
To use multiple readers you have to create them in the for loop and access them via the event object(e.targrt) in the callback.
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];
let reader = new FileReader();
reader.onloadend = this.handleFileRead;
reader.readAsText(fileitems);
}
}
handleFileRead = (e) => {
const content = e.targrt.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);

Get Base64 String of Ant Design Multi Upload list

Hi im making a multi upload files button with Ant Design. My goal is update state fileList with the list of file and convert originFileObj into base64 string. The problem is my function only returns one base64 string for all files in fileList. Here is my code:
import React from 'react';
import { Upload } from 'antd';
export default class MultiUpload extends React.Component {
constructor(props: any) {
super(props);
this.state = {
fileList: []
};
this.handleUpload = this.handleUpload.bind(this);
}
handleUpload = (info: any) => {
let fileList = [...info.fileList];
// Accept 5 files only
fileList = fileList.slice(-5);
fileList.forEach(function(file, index) {
let reader = new FileReader();
reader.onload = (e) => {
file.base64 = e.target.result;
};
reader.readAsDataURL(info.file.originFileObj);
});
this.setState({fileList: fileList});
};
componentDidUpdate(prevProps, prevState) {
console.log(this.state)
}
render() {
return (
<div>
<Upload
listType={"text"}
multiple={true}
onChange={this.handleUpload}
>
<button >
Upload
</button>
</Upload>
</div>
)
}
};
onŠ”hange function is called with an object with such fields
{
file: {/ * ... * /},
fileList: [/ * ... * /],
event: {/ * ... * /},
}
You always pass only the current file into readAsDataURL. Instead, you need to pass a file from the fileList.
handleUpload function should look something like this:
handleUpload = (info: any) => {
let fileList = [...info.fileList];
// Accept 5 files only
fileList = fileList.slice(-5);
fileList.forEach(function (file, index) {
let reader = new FileReader();
reader.onload = (e) => {
file.base64 = e.target.result;
};
reader.readAsDataURL(file.originFileObj);
});
this.setState({ fileList });
};

Input file(jpg/png) uploading and showing are not working in Reactjs?

File Button is not showing the jpeg image after uploading in locally
Below is the code i have written in react js...
categoryImageArray = [];
getCategoryImageLink = (e) => {
let files = e.target.files;
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = (e) => {
categoryImageArray.push(e.target.result);
}
}
and below is the JSX code
**IMG SRC**
<div>
<img src = { "'" + categoryImageArray[0] + "'" } />
</div>
Input File
<input type="file" onChange = { this.getCategoryImageLink } />
You have to use state for this,set the value of categoryImageArray in state and change it's value in getCategoryImageLink function
Try this.
getCategoryImageLink = (e) => {
let files = e.target.files;
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = (e) => {
this.setState({categoryImageArray: ...this.state.categoryImageArray,e.target.result});
}
}

ReactJS file upload

I am trying to upload a file using reactjs. I am not getting the right log. Before uploading, I wanted to see the output. But not getting the result.
Here what I have tried
state = {
selectedFile: null
}
fileChangedHandler = event => {
this.setState({
selectedFile: event.target.files[0]
})
console.log(this.state.selectedFile)
}
uploadHandler = () => {
const formData = new FormData()
var fd = formData.append("data", this.state.selectedFile, this.state.selectedFile.name)
console.log(fd)
}
render() {
return (
<div>
<input type="file" onChange={this.fileChangedHandler} />
<button onClick={this.uploadHandler}>Upload!</button>
</div>
);
}
Try this
// Create your FormData object
var formData = new FormData();
formData.append('key1', 'value1'); // Test data
formData.append('key2', 'value2'); // Test data
// Display the key/value pairs array
for (var pair of formData.entries()) {
console.log(pair);
}

Resources