reactjs - 获取 Ant Design Multi Upload 列表的 Base64 字符串
问题描述
嗨,我用 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 });
};
推荐阅读
- java - Spring Boot 属性解析不正确
- c++ - Check for end-of-list in boost::intrusive::list without container?
- javascript - 如何抓取网页内容需要点击按钮
- c# - ASP.NET 3.5 使用 System.Drawing.Printing PrintDocument 打印现有 PDF 文件
- python - 如何在 Django 中使用 __init__ 预填充模型表单字段中的值?
- c# - 通过 join 将 c# linq 转换为 sql 代码并进行优化
- html - 水平条在移动设备上未对齐
- css - reactjs中如何制作动画?
- reactjs - 我们什么时候使用 react 自定义钩子和 react 上下文?
- arrays - 在 swift 中,当在 modelArray 中附加模型时,计数显示 nil