您好,我正在使用 Ant Design 制作一个多文件上传按钮。我的目标是使用文件列表更新状态 fileList 并将 originFileObj 转换为 base64 字符串。问题是我的函数只为 fileList 中的所有文件返回一个 base64 字符串。这是我的代码:
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 函数是用具有此类字段的对象调用的
{
file: {/ * ... * /},
fileList: [/ * ... * /],
event: {/ * ... * /},
}
您始终只将当前文件传递给 readAsDataURL。相反,您需要从 fileList 传递一个文件。 handleUpload 函数应如下所示:
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 });
};
关于reactjs - 获取 Ant Design Multi Upload 列表的 Base64 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60604000/