File Upload empty on submit

Viewed 2746

I'm trying to upload an image using Axios inside an object. I can get a file using new FormData() and put it in an object, but submitting the image is empty. How do I upload a file in an object in combination with other JSON data?

import React, { useState } from 'react';
import axios from 'axios';

function UploadFiles() {
  const [submitFile, setSubmitFile] = useState({});

  const handleChange = e => {
    setSubmitFile(e.target.files[0]);
  };

  const handleSubmit = () => {
    const formData = new FormData();
    formData.append('document', submitFile);
    formData.append('Answer_name', 'image');
    formData.append('Document', true);
    formData.append('Answer', 'Got some data');

    console.log(submitData) // I get formData data

    const submitData = {
      UUID_Formulier: '117F994F-F803-7249-91E9-EE1E7B691DFF',
      answers: [formData], // this will be an empty object on calling axios.post
    };
    axios
      .post('/submit', submitData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then(() => {
        console.log('success');
      })
      .catch(() => {
        console.log('failed error');
      });
  };

  return (
    <div>
      <input type="file" name="image" onChange={handleChange} />
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
}

The image must be placed in the answers array. When I put FormData in the answers array, it's an empty object. How can I put file formData into a JSON object or array then submit all?

Using Square bracket notation doesn't create an array but strings, as shown below. enter image description here

2 Answers

All your data has to be added to the FormData object, to get the data in an array-like form you can try square bracket notation.

const formData = new FormData();
formData.append('UUID_Formulier', '117F994F-F803-7249-91E9-EE1E7B691DFF');
formData.append('answers[0][document]', submitFile);
formData.append('answers[0][Answer_name]', 'image');
formData.append('answers[0][Document]', true);
formData.append('answers[0][Answer]', 'Got some data'); 

console.log(formData) // I get formData data

axios
  .post('/submit', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
  .then(() => {
    console.log('success');
  })
  .catch(() => {
    console.log('failed error');
  });

};

Solved it by converting file into base64 string.

function getBase64(file) {
  return new Promise(function(resolve, reject) {
    const reader = new FileReader();
    reader.onload = function() {
      resolve(reader.result);
    };
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
}

const [form, setForm] = useState([]);
const fileFound = e.target.type === 'file' && e.target.files[0];

const promise = fileFound && getBase64(fileFound);

promise.then(function(result) {
   setForm([
      ...form,
      {
         UUID_Answer: 'image_name,
         Answer: '',
         Document: true,
         Document_Upload: result,
      },
   ]);
});

const submitData = {
    UUID_Formulier: '117F994F-F803-7249-91E9-EE1E7B691DFF',
    answers: form,
  };

axios
  .post('/submit', submitData)
  .then(() => {
    console.log('success');
  })
  .catch(() => {
    console.log('failed error');
  });
Related