如何使用 Node.js 和 Express 处理文件上传?

更新日期: 2024-02-21 阅读: 1.1k 标签: 文件

要学习本教程,您需要具备以下条件:

  • 您的计算机上安装了 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 install

2、生成的应用程序应具有以下目录结构:

.
├── 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.pug

3、在我们继续之前,请确保您能够运行应用程序并在浏览器中查看它,在 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 的响应。



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

链接: https://fly63.com/article/detial/12658

相关推荐

在js文件中引入另一个js文件的实现方法总汇

比如我写了一个JS文件,这个文件需要调用另外一个JS文件,该如何实现呢?这篇文章主要介绍:在js文件中引入另一个js文件的实现

如何使用 HTML Imports?

Web 组件从第一次被引入,经历了漫长的过程。其中某个组件可能真的会改变我们编写网站的方式,它就是 HTML Imports 。这种方法允许我们将 HTML 文档导入到其他的 HTML 文档中去

使用HTML5来实现本地文件读取和写入

最近有这样一个需求,就是在HTML页面中有个按钮导出,点击它,将构造一个文档并存储到本地文件系统中。另外还有个按钮,点击它,从本地文件系统中读取一个文件并对内容进行分析。

js获取文件真实类型/文件格式

在我们处理文件上传时候,通常情况下获取文件类型都是直接根据文件名后缀确定的,但是后缀名是可以随意修改的,比如界面要上传的是图片文件,如果客户端将一个exe文件改为gif后缀的文件,它照样可以上传上去。

什么是断点续传?前端如何实现文件的断点续传

什么是断点续传?就是下载文件时,不必重头开始下载,而是从指定的位置继续下载,这样的功能就叫做断点续传。前端通过FileList对象获取到相应的文件,按照指定的分割方式将大文件分段,然后一段一段地传给后端,后端再按顺序一段段将文件进行拼接。

使用HttpClient发送文件流到服务器端

适用场景: 网络绝对路径的URL文件或图片,不存储到本地,转换成stream,直接使用HTTPClient传送到SpringBoot的服务端,将文件存储下来,并返回一个文件地址。目前分层架构的系统越来越多这种需求,所以记录下来以备不时之需。

前端实现文件在线预览txt,pdf,doc,xls,ppt几种格式

做法就是使用iframe标签,只需要配置src就可以,根据文件后缀判断如果是office的类型就在url前加上https://view.officeapps.live.com/op/view.aspx?src=

前端实现文件下载功能

通过window.open()打开新页面下载文件;通过a标签打开新页面下载文件;通过文件流的方式下载;如何实现批量下载,且打包文件

form表单文件上传_multipart/form-data文件上传

form表单的enctype属性:规定了form表单数据在发送到服务器时候的编码方式.。application/x-www-form-urlencoded:默认编码方式,multipart/form-data:指定传输数据为二进制数据,例如图片、mp3、文件,text/plain:纯文本的传输。空格转换为“+”,但不支持特殊字符编码。

源文件是什么?

在开发软件的过程中,我们需要将编写好的代码(Code)保存到一个文件中,这样代码才不会丢失,才能够被编译器找到,才能最终变成可执行文件。这种用来保存代码的文件就叫做源文件(Source File)。

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!