Implementing File Uploads in Node.js Applications

HTML Form Configuration

For file uploads, the HTML form must include the enctype="multipart/form-data" attribute and use the POST method:

User Registration
Username:
Password:
Confirm Password:
Profile Image:

Setting Up Node.js Environment

Install the multer middleware package to handle file uploads:

npm install --save multer

Backend Implementation

In your Node.js application, configure multer and implement the file upload endpoint:

const express = require('express');
const fs = require('fs');
const path = require('path');
const multer = require('multer');
const app = express();

// Configure file storage
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadPath = './uploads/profiles';
    // Ensure upload directory exists
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    // Create unique filename to avoid conflicts
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// User registration endpoint with file upload
app.post('/api/user/create', upload.single('profile_image'), function (req, res, next) {
  try {
    // Check if file was uploaded
    if (!req.file) {
      return res.status(400).({ error: 'No file uploaded' });
    }

    // Get user data from form
    const userData = {
      username: req.body.user_name,
      password: req.body.user_password,
      confirmPassword: req.body.confirm_password
    };

    // Basic validation
    if (!userData.username || !userData.password) {
      return res.status(400).({ error: 'Username and password are required' });
    }

    if (userData.password !== userData.confirmPassword) {
      return res.status(400).({ error: 'Passwords do not match' });
    }

    // File information
    const fileInfo = {
      originalName: req.file.originalname,
      filename: req.file.filename,
      path: req.file.path,
      size: req.file.size,
      mimetype: req.file.mimetype
    };

    console.log('Uploaded file:', fileInfo);

    // Here you would typically save user data to database
    // and associate the uploaded file with the user

    res.status(200).({ 
      message: 'User created successfully',
      user: userData,
      file: fileInfo
    });

  } catch (error) {
    console.error('Error during file upload:', error);
    res.status(500).({ error: 'Internal server error' });
  }
});

Security Considerations

When implementing file uploads, consider these security practices:

  • Validate file types to prevent uploading executable files
  • Limit file size to prevent denial-of-service attacks
  • Sanitize file names to prevent path traversal attacks
  • Store uploaded files outside the web root directory

Tags: Node.js file-upload multer web-development Backend

Posted on Mon, 11 May 2026 03:49:00 +0000 by metalblend