Pass FormData object from Client to Server

When you are making a POST request which has input field value (“text”, “file”) and you want to pass these data from client to server, this won’t be straight forward you need to pass them as FormData. It’s useful when you need to send form data to RESTful API endpoints, for example to upload file using fetch or Axios. Let’s consider a scenario where you have a form and inside that form you have two input fields(input type text, file).

const [name, setName] = React.useState('');
const [file, setFile] = React.useState('');

return (
  <form onSubmit={addUser}>
    <input type="text" value={name} onChange={e => setName(e.target.value)} />
    <input type="file" accept="image/*" onChange={handleFileChange} />
    <button>Add User</button>
  </form>
)

Lets see the handleFileChange,

const handleFileChange = e => {
  setFile(e.target.files[0]);
}

The addUser function will be,

const addUser = e => {
  e.preventDefault();

  const formData = new FormData();
  formData.append("name", name.current.value);
  formData.append("file", file);

  axios
    .post("/user", formData, {
      headers: {
        "Content-type": "multipart/form-data"
      }
    })
    .then(res => console.log(res))
    .catch(err => console.log(err))
}

new FormData() helps you to pass input type text, file as key-value pair. axios or fatch can accept a FormData as a body. It is encoded and sent out with "Content-type": "multipart/form-data".

This is all about client side work. Lets do some server side things using express.js.

As we are passing a input type=”file”, so in order to get or parse the value we need to use a package called express-fileupload(there are many package available).

npm install --save express-fileupload

Add this in your server file,

const fileUpload = require("express-fileupload");

app.use(fileUpload()); 

Now the express-fileupload package is available in our entire server folder.

We can grab the name, file from our controller,

exports.addUser = (req, res) => {
  const name = req.body.name;
  const file = req.files.file;
}

The name is the actual name and the file is an object containing the file information that we pass from client side.

Leave a Comment

Your email address will not be published. Required fields are marked *