Upload Form Data to Api Endpoint Using Multer

Upload Files to Next.js With API Routes

Night launch of a Space-X satellite showing a brilliant light trail against a dark sky

Photo by SpaceX on Unsplash

I am going to give a brief overview of how to upload files with React and Next.js API routes. In this article, I will assume you are familiar with calculation npm packages and with using Next.js, and that you have created an API road before.

Below is a simple example of a Next.js API route.

Next API route

To make things easier when it comes to calculation middleware to the API routes, nosotros are going to use the side by side-connect library.

next-connect

next-connect is a router and middleware layer for Next.js, Micro, or Node.js HTTP servers. It will make method routing and adding middleware easier.

Later on calculation the next-connect library, nosotros can refactor the above API road code into the next-connect format below. The syntax is very similar to Express.js.

next-connect api route

Now that we have updated our Next.js API route we tin can add the Multer middleware library to next-connect to handle that file upload for us.

Multer

Multer is a Node middleware for handling multipart/form information and is primarily used for uploading files.

After adding the Multer library, permit's add it to the API road lawmaking above. Read the comments in the case below for how we add together Multer to next-connect.

  • Looking at lines 6–eleven, we create a Multer case and provide a config object to ready the storage type. Nosotros set the destination to public/uploads so the uploaded files could be publicly accessed by the Next.js app. The destination can be a string or a role. When destination is a function, you are responsible for creating the directory structure. For the filename, we use a role to get the original name from the uploaded file.
  • Looking at lines 16 & 19, we create the bodily middleware when doing upload.array('theFiles'). Annotation: Nosotros are using .assortment() in the example above, which allows us to upload multiple files, but Multer has other methods, like .unmarried(), for only uploading a single file. Read the docs and run across which i is best for your situation. Finally, we laissez passer the created middleware to apiRoute.use() where next-connect will utilise it inside the API route.

That is information technology for setting upwardly a bones implementation of Multer, simply there is ane more step to finish off our File Upload API route.

Next.js API Route Config

There is one last step we cannot forget about. By default, Next.js automatically parses the API request body. Nosotros need to disable the trunk parsing and so we tin consume the body equally a stream to upload the files.

Every API route can export a config object to change the default configs.

Below, notice the config object after the export default apiRoute;. This is how nosotros use the Next.js custom config object to disable torso parsing.

Next.js API road config body parser

Final API route lawmaking

Here is all the code needed to upload files with a Next.js API route:

React and axios

To finish off the file upload in Adjacent.js, we need to create some React components and use axios to make the file upload requests.

Beneath is an animation of how our app will piece of work to allow us to upload single or multiple files with the Adjacent.js API route we created above.

animation of the author's app uploading files using Next API route

Before we get into the React code, let's wait at how nosotros should set up axios to handle uploading files while besides giving us a way to show the progress of the file(southward) being uploaded.

axios

axios is a promise-based HTTP client for the browser and Node.

Before I show you React and axios together, I want to highlight the axios code past itself.

  • Line 3 we need to fix the request headers with a content-blazon of multipart/course-data and then the API will know what to do with the received data.
  • Lines 4–6 is where we get the progress status for the file(s) being uploaded.
  • Line nine is the Mail request to the '/api/uploads' API road we created to a higher place. We pass the formData and the config object to brand this request complete.

React

Beneath is the axios code within a React page component. Find the onChange existence passed to the UiFileInputButton component. The UiFileInputButton component is responsible for creating the FormData object that we pass to the onChange method that will make the upload request to our API road.

One important thing to indicate out is the uploadFileName value of 'theFiles'. If you look at the API route code, you will as well come across that value in upload.array('theFiles'). This is the field name, and both React and the API route need to accept the same value to piece of work.

The TypeScript UiFileInputButton file beneath is but a wrapper around a file input and a button. The one main section I desire to signal out is the onChangeHandler code. Looking at lines 22–28, you will see we accept the files given to us from the effect.target.files and suspend them to a FormData object so the parent lawmaking simply needs to handle the FormData for the request.

Determination

I've given y'all a brief overview of the lawmaking needed to upload files with React and Side by side.js API routes. This was an experiment for me, and I have not deployed the code to any hosting solutions. Now it is up to you to inquiry how yous can take this code and make information technology production-set up for your React/Side by side.js application.

Bank check out my example branch to come across this code working.

If you similar this article please share information technology, read my other articles and/or sign up to Medium with my referral link below. Thanks!

-

jeanneretfurday.blogspot.com

Source: https://betterprogramming.pub/upload-files-to-next-js-with-api-routes-839ce9f28430

0 Response to "Upload Form Data to Api Endpoint Using Multer"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel