惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Heimdal Security Blog
A
Arctic Wolf
K
Kaspersky official blog
V
Vulnerabilities – Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Simon Willison's Weblog
Simon Willison's Weblog
L
LINUX DO - 热门话题
MongoDB | Blog
MongoDB | Blog
T
Threat Research - Cisco Blogs
D
Docker
爱范儿
爱范儿
T
Tenable Blog
C
Check Point Blog
B
Blog
C
Cisco Blogs
Vercel News
Vercel News
The Cloudflare Blog
T
Threatpost
NISL@THU
NISL@THU
T
Tor Project blog
V2EX - 技术
V2EX - 技术
P
Palo Alto Networks Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tailwind CSS Blog
G
GRAHAM CLULEY
P
Privacy & Cybersecurity Law Blog
SecWiki News
SecWiki News
博客园 - 司徒正美
S
Security @ Cisco Blogs
GbyAI
GbyAI
S
Secure Thoughts
Microsoft Security Blog
Microsoft Security Blog
The Register - Security
The Register - Security
Recorded Future
Recorded Future
Cloudbric
Cloudbric
Webroot Blog
Webroot Blog
N
News and Events Feed by Topic
Y
Y Combinator Blog
博客园_首页
T
Troy Hunt's Blog
The Hacker News
The Hacker News
雷峰网
雷峰网
Google DeepMind News
Google DeepMind News
U
Unit 42
AWS News Blog
AWS News Blog
PCI Perspectives
PCI Perspectives
V
Visual Studio Blog
博客园 - 聂微东
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Storing Uploaded Files and Serving Them in Express
SATYA SOOTAR · 2026-05-10 · via DEV Community

Hello readers 👋, welcome to the 13th blog in our Node.js series!

In the last post, we learned how Multer helps us accept file uploads in Express, whether single files or multiple files. We configured a disk storage engine and saw how req.file and req.files give us all the details about what arrived. But one question remained unanswered: where do the uploaded files actually live, and how do clients get them back?

Today we're going to close that loop. We'll talk about storage choices, how to serve uploaded files so they're accessible via a URL, and crucial security practices that keep your application safe. By the end, you'll have a complete picture of the upload‑serve lifecycle.

Let's jump in.

Where uploaded files are stored

When Multer saves a file on the server, it places it into a folder that you specify via the destination callback. In our previous example, we used an uploads folder at the root of our project. After a few uploads, the folder might look something like this:

project/
├── uploads/
│   ├── avatar-1680000000-123456789.png
│   ├── avatar-1680000010-987654321.jpg
│   └── cover-1680000020-456789123.jpeg
├── server.js
└── package.json

Enter fullscreen mode Exit fullscreen mode

The actual filenames are generated by the filename callback (often using a timestamp and a random number to avoid collisions). The original name is still available inside req.file.originalname, but on disk we keep a sanitized, unique name.

Local storage vs external storage concept

In development and small applications, storing files on the local filesystem is perfectly fine. It's simple and needs no extra setup. But as your application grows, you'll often hear about external storage services like Amazon S3, Google Cloud Storage, or Cloudinary. These services store files separately from your Node.js server, which brings several benefits:

  • Your server's disk space isn't used by user files.
  • The files can be served to clients directly from a CDN, reducing load on your application server.
  • Scaling becomes easier because the storage layer is independent.

For this post, we'll focus entirely on local storage because that's where most people start. We'll mention how to serve those local files directly to clients. Later, when you move to cloud storage, the ideas of URLs and security transfer easily.

Serving static files in Express

After a file is uploaded and stored on disk, you typically want to make it accessible through a URL so that a client (browser, mobile app) can download or display it. Express provides a built‑in middleware called express.static exactly for this purpose.

express.static takes a folder path and serves all files inside it as static assets. For example:

const express = require('express');
const app = express();

// Serve files from the 'uploads' folder at the '/files' URL path
app.use('/files', express.static('uploads'));

Enter fullscreen mode Exit fullscreen mode

Now, if there is a file uploads/avatar-123456.png, it becomes available at http://localhost:3000/files/avatar-123456.png. The URL path you choose (/files) can be anything; it doesn't have to match the folder name.

A common practice is to serve the uploads folder under a dedicated path like /uploads or /files to keep the URL structure clear.

Setting up the complete flow

Let's combine Multer and static serving into a single Express app to see the full picture:

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

const app = express();
const port = 3000;

// Ensure uploads folder exists
const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir);
}

// Multer configuration
const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, 'uploads/'),
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + uniqueSuffix + ext);
  }
});
const upload = multer({ storage });

// Serve uploaded files statically
app.use('/files', express.static('uploads'));

// Upload route
app.post('/upload', upload.single('photo'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: 'No file uploaded' });
  }
  // Build the public URL
  const fileUrl = `http://localhost:${port}/files/${req.file.filename}`;
  res.json({
    message: 'File uploaded successfully',
    url: fileUrl
  });
});

app.listen(port, () => console.log(`Server running on port ${port}`));

Enter fullscreen mode Exit fullscreen mode

After uploading, the client receives a JSON response containing the direct URL. It can then use that URL to display an image, download a document, or simply check the file.

Accessing uploaded files via URL

The key insight is that the public URL is built from three parts:

  • Base URL of your server (e.g., http://localhost:3000)
  • Static serving path (e.g., /files)
  • Filename on disk (the unique name generated by Multer)

In the route handler, req.file.filename gives us the exact name stored on disk. Concatenating these pieces gives a valid URL that Express will serve from the uploads folder.

For a more production‑ready approach, you'd likely construct the URL from a configuration setting, not hardcode localhost. For example:

const baseUrl = process.env.BASE_URL || `http://localhost:${port}`;
const fileUrl = `${baseUrl}/files/${req.file.filename}`;

Enter fullscreen mode Exit fullscreen mode

Now clients always get the correct URL regardless of the environment.

Security considerations for uploads

File uploads are powerful but also a potential attack vector if not handled carefully. Here are some essential safe‑handling practices that every developer should follow.

1. Limit allowed file types

Never accept arbitrary file types. Use Multer's fileFilter to check the MIME type or file extension before writing to disk. For example, if you expect images:

const upload = multer({
  storage,
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif/;
    const mimeType = allowedTypes.test(file.mimetype);
    const extName = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    if (mimeType && extName) {
      return cb(null, true);
    }
    cb(new Error('Only image files are allowed'));
  }
});

Enter fullscreen mode Exit fullscreen mode

2. Restrict file size

You can set a limits object on the Multer instance to reject files that are too large:

const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 } // 5 MB
});

Enter fullscreen mode Exit fullscreen mode

This prevents someone from filling up your server's disk with a single request.

3. Rename files to avoid path traversal

Never trust the original filename directly in the storage path. Always generate a new name, as we did with the filename callback. Using Date.now() and a random number makes it nearly impossible for an attacker to guess the filename. Also avoid including user‑supplied strings in the path to prevent directory traversal attacks (e.g., ../../../etc/passwd).

4. Store uploaded files outside the public web root

If possible, keep the uploads folder outside the main Express static folder that is openly served. In our setup, we used /files explicitly, but the uploads folder itself is not automatically exposed except through that route. Still, it's a good idea to store uploads in a directory that is not directly under the static root, and then use express.static with an absolute path to serve it under a specific URL prefix. This prevents direct access via path guessing.

5. Do not execute uploaded files

Make sure your static file serving middleware only serves files with safe content types. For example, if someone uploads a .php or .js file and you serve it via express.static, a browser might try to interpret it as code, especially if served with the wrong Content-Type. Express/Node.js static middleware sends files with an appropriate MIME type based on the extension, which usually prevents execution. Still, it's wise to limit accepted extensions and avoid storing executable scripts in the uploads folder.

6. Scan for malware (advanced)

For high‑security applications, you can integrate virus scanning tools that inspect uploaded files before they're stored. This is beyond the scope of this post, but keep it in mind for production systems.

Conclusion

Storing and serving uploaded files completes the file upload puzzle. By using Multer's disk storage and Express's static middleware, you can quickly give your users the ability to upload content and retrieve it via clean URLs. Add a few security precautions, and you have a robust foundation that works for development and small production apps.

Let's quickly recap:

  • Uploaded files can be stored locally in a project folder (e.g., uploads/) or externally on cloud services for scalability.
  • express.static lets you serve the files under a URL prefix, making them accessible to clients.
  • Building a file URL combines the base URL, the static serving path, and the unique filename stored on disk.
  • Security is essential: limit file types and sizes, rename files, avoid executable files, and store uploads outside the main public root if possible.
  • A clear folder structure and the static middleware together create an intuitive upload‑serve flow.

Now you have the full cycle: receiving files and giving them back. In the next post, we'll explore something new, maybe working with databases or error handling. See you then!


Hope you found this helpful! If you spot any mistakes or have suggestions, let me know. You can find me on LinkedIn and X, where I post more about web development.