0

React js antd upload component send image base64 to the python server

Image upload send to the server base64

Without using formData method

1

2 Answers 2

1

You need input type="file" to select an image:

    <input
        type="file"
        onChange={onChange}
      />

Function to convert file to base64:

const convertBase64 = (file) => new Promise((resolve, reject) => {
  const fileReader = new FileReader()
  fileReader.readAsDataURL(file)

  fileReader.onload = () => {
    resolve(fileReader.result)
  }

  fileReader.onerror = (error) => {
    reject(error)
  }
})

And onChange handler:

const onChange = async event => {
  const file   = event.target.files[0]
  const base64 = await convertBase64(file)

  const formData = new FormData()

  formData.append('file-key', base64)

// --- now you can send base64 file to server --- //
  await fetch('api/{your-api-here}', {
    method: 'POST',
    body:   formData,
  })
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this one

Please refer antd doc for uploading. https://ant.design/components/upload

handleChange= (info: any) => {
 let fileList = [...info.fileList];

  fileList.forEach(function (file, index) {
   let reader = new FileReader();
   reader.onload = (e) => {
     file.base64 = e.target.result;
   };
   reader.readAsDataURL(file.originFileObj);
 });

 this.setState({ fileList });
};

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.