如何使用 Node.js 在服务器端处理文件上传?

解释了如何在 Node.js 中使用 Express 和 Multer 处理文件上传。提供了一个简单的示例,展示了从设置项目到处理上传的完整流程,并讨论了其他替代方案和安全注意事项。

Node.js 中等 文件上传 Express Multipart

在 Node.js 环境中向服务器上传文件通常指创建一个 Node.js 应用作为服务器,接收客户端通过 HTTP POST 请求上传的文件。主流方法是使用框架(如 Express)配合中间件(如 Multer)简化处理过程。以下是基于可参考信息实现的步骤说明和代码示例。

1. 核心方法

  • 使用 Express 框架构建服务器,处理请求响应。
  • 采用 Multer 中间件(推荐)或 formidable 解析 multipart/form-data 格式上传数据。
  • Multer 直接将文件保存到本地目录,适合简单上传;formidable 解析字段和文件流。

2. 快速步骤:使用 Express + Multer

(a) 初始化项目: 创建并安装依赖:

   npm init -y
   npm install express multer

(b) 创建 Express 应用: 在 app.js 中设置服务器端代码:

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

   // 配置 Multer:上传到 './uploads' 目录,保留原始文件名
   const storage = multer.diskStorage({
     destination: (req, file, cb) => cb(null, './uploads'),
     filename: (req, file, cb) => cb(null, file.originalname)
   });
   const upload = multer({ storage });

   // Handle file upload
   app.post('/upload', upload.single('file'), (req, res) => {
     res.send('文件上传成功!文件名: ' + req.file.originalname);
   });

   // Start server
   app.listen(3000, () => console.log('服务器在 3000 端口运行'));

(c) 前端请求示例: 客户端发送请求使用:

   <form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
     <input type="file" name="file">
     <input type="submit" value="上传">
   </form>

3. 处理上传类型

  • 单文件: upload.single('字段名')
  • 多文件: upload.array('字段名')

4. 其他方案:流处理和 formidable

  • 使用 HTTP 模块 + formidable:
     const http = require('http');
     const formidable = require('formidable');
     const path = require('path');
       
     const server = http.createServer((req, res) => {
       if (req.url === '/upload' && req.method === 'POST') {
         const form = new formidable.IncomingForm();
         form.uploadDir = path.join(__dirname, 'uploads'); // 保存目录
           
         form.parse(req, (err, fields, files) => {
           if (err) res.end('Error: ' + err.message);
           else res.end(`上传成功: ${files.file.path}`);
         });
       }
     });
     server.listen(8080);
    

5. 安全注意事项

  • 验证文件类型:检查 MIME 类型以防止恶意上传。
  • 设置文件大小限制:在 multer 或通过 maxFileSize 参数。
  • 使用 express-fileupload 库作为替代.

通过这种方法,Node.js 可高效处理浏览器端文件上传至服务器端存储。