reactjs - 获取 Ant Design Multi Upload 列表的 Base64 字符串

标签 reactjs typescript antd

您好,我正在使用 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/

相关文章:

reactjs - 无法读取 react 中未定义的属性 'push'

javascript - 正在设置 React useImperativeHandle 和 forwardRef,引用似乎没有更新

typescript - 如何在 TypeScript 中正确使用函数的构造签名

javascript - Ant-Design CSS 无法正确加载

javascript - antd上传API : how to return promise

javascript - 获取 ant.design 表列中另一列的值?

reactjs - 如何根据 react 中单击的按钮为按钮分配不同的值

javascript - 以编程方式更改 Redux-Form 复选框字段值

typescript - ()=>any 和 {() :any} in Typescript 有什么区别

javascript - 使用对象键作为另一个对象的键