0
0
ExpressHow-ToBeginner · 4 min read

How to Save File to Disk in Express: Simple Guide

To save a file to disk in Express, use middleware like multer to handle file uploads and specify a destination folder. The uploaded file will be saved automatically to the disk when you configure multer with a storage destination.
📐

Syntax

Use multer middleware to handle file uploads in Express. Configure it with a storage option that sets the destination folder and filename. Then use upload.single('fieldname') or upload.array('fieldname') in your route to process the file.

  • multer.diskStorage(): Defines where and how to save files.
  • destination: Folder path to save files.
  • filename: Function to set saved file name.
  • upload.single('file'): Middleware to handle one file upload.
javascript
import express from 'express';
import multer from 'multer';

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // folder to save files
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname); // save with original name
  }
});

const upload = multer({ storage });

const app = express();

app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File saved to disk');
});
💻

Example

This example shows a complete Express server that saves an uploaded file to the uploads/ folder using multer. The file is sent from a form field named file. After upload, the server responds with a confirmation message.

javascript
import express from 'express';
import multer from 'multer';
import fs from 'fs';

// Ensure uploads folder exists
if (!fs.existsSync('uploads')) {
  fs.mkdirSync('uploads');
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, `${Date.now()}-${file.originalname}`);
  }
});

const upload = multer({ storage });
const app = express();

app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded');
  }
  res.send(`File saved as ${req.file.filename}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // After POST /upload with file field: File saved as 1687000000000-filename.ext
⚠️

Common Pitfalls

  • Not creating the destination folder before saving files causes errors.
  • Using upload.single('wrongField') with a mismatched form field name results in no file saved.
  • Not handling errors from multer middleware can crash the server.
  • Saving files without unique names may overwrite existing files.

Always validate the uploaded file and handle errors gracefully.

javascript
/* Wrong: destination folder missing */
const storageWrong = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'missing_folder/'); // folder does not exist
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  }
});

/* Right: create folder before saving */
import fs from 'fs';
if (!fs.existsSync('uploads')) {
  fs.mkdirSync('uploads');
}
📊

Quick Reference

  • multer.diskStorage: Configure file saving location and name.
  • upload.single('field'): Middleware for single file upload.
  • upload.array('field'): Middleware for multiple files.
  • req.file: Access uploaded file info after upload.
  • Ensure upload folder exists before saving files.

Key Takeaways

Use multer middleware with diskStorage to save files to disk in Express.
Always create the destination folder before uploading files to avoid errors.
Match the form field name with multer's upload.single or upload.array method.
Handle errors from multer to keep your server stable.
Use unique filenames to prevent overwriting existing files.