Upload a File with ReactJS

Upload a File with ReactJS

There are multiple ways to upload a file using React. I’m going to explain the steps to upload a single file, multiple files, and files and data in React.

Originally published by James King at https://upmostly.com

We’re going to cover every scenario you might come across to upload a file from inside of a React component. These are:

  • Upload one file
  • Upload multiple files
  • Upload files and other types of data in a single request

How to Upload a File in React

We’ll start with the easiest and most common scenario, which is how to upload a single file to a server from a React component.

Any type of file upload in React, or any front-end JavaScript library for that matter, requires an HTTP library to send the file data to a server.

I’m using the Fetch HTTP library in the following examples, but you can easily adapt them to work with other HTTP libraries like Axios or SuperAgent.

function uploadFile(file) {
  fetch('https://path/to/api', {
    // content-type header should not be specified!
    method: 'POST',
    body: file,
  })
    .then(response => response.json())
    .then(success => {
      // Do something with the successful response
    })
    .catch(error => console.log(error)
  );
}

The example above uses a function, uploadFile, which takes a file object and passes that object to a POST request.

There are two things you need to remember when POSTing a file object:

  • Never set the Context-Type Header.
  • Pass the whole file object (Blob) to the body of the request.

Content-Type and Uploading a File

If you’ve made API requests in the past, then you probably used ‘application/json‘ as your ‘content-type’ header.

You do not need to set the content-type header when sending a file in a POST request.

File objects (Blobs) are not JSON, and therefore using an incorrect content-type will cause the request to fail. Web browsers automatically set the content-type header when sending a file in a POST request.

How to Upload Multiple Files in React using FormData

When we need to upload multiple files using Fetch, we have to use a new type of object called FormData.

FormData allows us to append multiple key/value pairs onto the object. After we’re done appending, we then pass it to the POST request’s body.

Let’s see an example of this below:

function uploadFile(files) {
  
  var formData = new FormData();
  
  files.map((file, index) => {
    formData.append(`file${index}`, file);
  });
  
  fetch('https://path/to/api', {
    // content-type header should not be specified!
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(success => {
      // Do something with the successful response
    })
    .catch(error => console.log(error)
  );
}

How to Upload Multiple Files and Other Data in React

There may be times when you need to send files and other data in a POST request. This can sometimes be referred to as multipart data.

For example, you may have a form which asks for a user’s first and last name, as well as a profile picture for their account avatar.

In this case, you’d want to use FormData again to send the file as well as the first name and last name. Let’s see how we’d use FormData to help us send all of this data together:

function uploadFile(files, user) {
  
  var formData = new FormData();
  
  files.map((file, index) => {
    formData.append(`file${index}`, file);
  });
  
  formData.append('user', user);
  
  fetch('https://path/to/api', {
    // content-type header should not be specified!
    method: 'POST',
    body: formData,
  })
    .then(response => response.json())
    .then(success => {
      // Do something with the successful response
    })
    .catch(error => console.log(error)
  );
}

 We’re simply using the formData.append method to create another key named ‘user’, and then passing the user object into the value of that key.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about React

React - The Complete Guide (incl Hooks, React Router, Redux)

Modern React with Redux [2019 Update]

Best 50 React Interview Questions for Frontend Developers in 2019

JavaScript Basics Before You Learn React

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Reactjs vs. Angularjs — Which Is Best For Web Development

React + TypeScript : Why and How

How To Write Better Code in React

React Router: Add the Power of Navigation

Getting started with React Router

Using React Router for optimizing React apps

reactjs javascript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

What is ECMAScript and How is it Different From JavaScript?

Many times developers use JavaScript and ECMAScript synonymously for each other. Though they are very closely linked to each other, it does not mean they are the same thing.here is a complete story on the history of JavaScript and how it came into existence. To cut the long story short, ECMA in ECMAScript refers to Europen Computer Manufacturers Association to which JavaScript 1.1 was submitted for standardization back in the year 1997.

Data Types In JavaScript

JavaScript data types are kept easy. While JavaScript data types are mostly similar to other programming languages; some of its data types can be unique. Here, we’ll outline the data types of JavaScript.

Forms of Composition in JavaScript and React

One of the core ideas in functional programming is composition: building larger things from smaller things. The canonical example of this idea should be familiar with legos.

JavaScript Memory Management System

The main goal of this article is help to readers to understand that how memory management system performs in JavaScript. I will use a shorthand such as GC which means Garbage Collection. When the browsers use Javascript, they need any memory location to store objects, functions, and all other things. Let’s deep in dive that how things going to work in GC.