如何使用 Node.js 和 Express 处理文件上传?
要学习本教程,您需要具备以下条件:
- 您的计算机上安装了 Node.js。
- JavaScript 和 Express 的基础知识。
- 文本编辑器或轻量级集成开发环境(如 Visual Studio Code)。
概述
为了允许上传文件,您将:
- 创建一个带有表单的网页,让用户选择要上传的文件。
- 创建一个 Express 路由处理程序来处理上传的文件。
当然,你还需要对每个上传的文件做一些处理!在本教程中,我们将编写 JavaScript 代码来显示文件的一些信息,并使用 Verisys Antivirus api 扫描文件是否有恶意软件。
注意事项:
- Verisys Antivirus API 是一种语言无关的 REST API,可在恶意软件到达服务器之前将其拦截在边缘。
- 通过扫描用户生成的内容和上传的文件,Verisys Antivirus API 可以阻止危险的恶意软件到达您的应用程序和服务以及最终用户。
项目设置
第一步是创建并初始化一个新的 Express 项目。
1、打开终端或命令提示符,导航到要存储项目的目录,然后运行以下命令:
npx express-generator --view=pug myapp
cd myapp
npm install2、生成的应用程序应具有以下目录结构:
.
├── app.js
├── package.json
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
├── views
│ ├── error.pug
│ └── index.pug
│ └── layout.pug3、在我们继续之前,请确保您能够运行应用程序并在浏览器中查看它,在 MacOS、Linux 或 Windows 上的 Git Bash 中,使用此命令运行应用程序:
DEBUG=myapp:* npm start或者在 Windows 下使用此命令:
set DEBUG=myapp:* & npm start或 Windows Powershell 的此命令:
$env:DEBUG='myapp:*'; npm start然后在浏览器中导航至 http://localhost:3000 访问该应用程序,您应该会看到一个类似下面的页面:

4、在命令提示符下点击 CTRL-C 停止服务器。
5、接下来,我们要添加几个 NPM 软件包:
- 我们将添加一个软件包,以便更轻松地处理文件上传。这里有几种选择,其中最流行的是 Multer、Formidable 和 express-fileupload--它们都相当类似,在本教程中,我们将使用 express-fileupload
- 在本教程中,我们将使用 Verisys Antivirus API 扫描文件以查找恶意软件,因此我们将添加一个软件包,以便更轻松地进行外部 HTTP 请求。流行的选择包括 Axios 和 node-fetch(本文将使用 node-fetch)。
我们还将添加 form-data 软件包,以便处理用于执行文件上传的多部分表单数据:
npm install express-fileupload
npm install node-fetch@^2.6.6
npm install form-data代码编写
在编写 JavaScript 代码处理文件上传之前,我们先创建一个简单的网页,让最终用户选择要上传的文件。
更新 myapp/views/index.pug 的内容,使其包含以下内容:
extends layout
block content
h1= title
p Welcome to #{title}
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>1、提交表单后,文件将被发送到 /upload 处的路由--下一步是创建路由和路由处理程序。
const express = require('express');
const fetch = require('node-fetch');
const fileUpload = require('express-fileupload');
const FormData = require('form-data');
const fs = require('fs');
const router = express.Router();
router.use(fileUpload({
// Configure file uploads with maximum file size 10MB
limits: { fileSize: 10 * 1024 * 1024 },
// Temporarily store uploaded files to disk, rather than buffering in memory
useTempFiles : true,
tempFileDir : '/tmp/'
}));
router.post('/', async function(req, res, next) {
if (!req.files || !req.files.file) {
return res.status(422).send('No files were uploaded');
}
const uploadedFile = req.files.file;
// Print information about the file to the console
console.log(`File Name: ${uploadedFile.name}`);
console.log(`File Size: ${uploadedFile.size}`);
console.log(`File MD5 Hash: ${uploadedFile.md5}`);
console.log(`File Mime Type: ${uploadedFile.mimetype}`);
// Scan the file for malware using the Verisys Antivirus API - the same concepts can be
// used to work with the uploaded file in different ways
try {
// Attach the uploaded file to a FormData instance
var form = new FormData();
form.append('file_name', uploadedFile.name);
form.append('file', fs.createReadStream(uploadedFile.tempFilePath), uploadedFile.name);
const headers = {
'X-API-Key': '<YOUR API KEY HERE>',
'Accept': '*/*'
};
// Send the file to the Verisys Antivirus API
const response = await fetch('https://eu1.api.av.ionxsolutions.com/v1/malware/scan/file', {
method: "POST",
body: form,
headers: headers
});
// Did we get a response from the API?
if (response.ok) {
const result = await response.json();
// Did the file contain a virus/malware?
if (result.status === 'clean') {
return res.send('Upload successful!');
} else {
return res.status(500).send('Uploaded file contained malware!');
}
} else {
throw new Error('Unable to scan file: ' + response.statusText);
}
} catch (error) {
// Forward the error to the Express error handler
return next(error);
} finally {
// Remove the uploaded temp file
fs.rm(uploadedFile.tempFilePath, () => {});
}
});
module.exports = router;该处理程序首先会将文件信息打印到控制台,以便查看收到了什么。然后,它将文件上传到 Verisys Antivirus API,以扫描文件中是否有恶意软件--请注意,X-API-Key 需要替换为真正的 API 密钥才能真正扫描文件。没有 API 密钥?现在就订阅!
2、更新 myapp/app.js 的内容,使其包含以下内容:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var uploadRouter = require('./routes/upload');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/upload', uploadRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;我们只在 Express 生成器提供的默认代码中添加了两行(上面的第 9 行和第 25 行),告诉 Express 在 /upload 路由中使用我们的 upload.js 路由器。
测试文件上传
现在我们可以测试了!
- 首先,使用与之前相同的命令启动 Node.js 服务器
- 打开浏览器并导航至 http://localhost:3000
- 浏览以选择文件,然后按上传按钮
如果一切设置正确,您应该会看到有关文件的信息被打印到控制台,而您在浏览器中看到的内容将取决于 Verisys Antivirus API 的响应。

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!