Examples
Node.js File Upload
Handling File Uploads
Node.js file upload with multer processes multipart/form-data.
Introduction to File Uploads in Node.js
Uploading files is a common requirement in web applications, whether it's for profile pictures, documents, or other media files. In Node.js, handling file uploads efficiently can be achieved using the Multer library. Multer is a middleware for handling multipart/form-data
, which is mainly used for uploading files.
Setting Up Multer
To get started with file uploads in Node.js, you need to install the Multer package. You can do this using npm:
Basic Configuration of Multer
Once Multer is installed, you can set up a basic file upload using an Express server. Here's a simple example to demonstrate the process:
In this example, we create an Express application and configure Multer to save uploaded files to the uploads
directory. The upload.single('file')
method is used to handle single file uploads, where 'file'
is the name of the form field containing the file.
Handling Multiple File Uploads
Multer also supports multiple file uploads. You can handle multiple files by using the upload.array()
method:
In this setup, the upload.array('files', 12)
method allows for the uploading of up to 12 files through the form field named 'files'
.
Customizing File Storage
You can customize the storage location and file naming by using Multer's diskStorage
method. This allows more control over how files are stored:
Here, we define a custom storage engine where the files are saved to the uploads
directory, and the file names include the original field name followed by a timestamp to ensure uniqueness.
Conclusion
File uploads in Node.js can be handled efficiently using the Multer middleware. By configuring Multer appropriately, you can easily manage both single and multiple file uploads, as well as customize the storage options to meet your application's requirements. With Multer, processing multipart/form-data
becomes straightforward and efficient.
Examples
- Previous
- Authentication
- Next
- Real-Time Chat