首页 > 解决方案 > 获取 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>
    )
  }
};

标签: reactjstypescriptantd

解决方案


使用具有此类字段的对象调用 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 });
  };

推荐阅读