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 });
};
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