Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Base64 String of Ant Design Multi Upload list

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>
    )
  }
};
like image 725
Lee Avatar asked Sep 16 '25 01:09

Lee


1 Answers

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 });
  };
like image 52
Andrey Avatar answered Sep 18 '25 15:09

Andrey