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

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

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

  • 您的计算机上安装了 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://www.fly63.com/article/detial/12658

h5移动端实现图片文件上传

PC端上传文件多半用插件,引入flash都没关系,但是移动端要是还用各种冗余的插件估计得被喷死,项目里面需要做图片上传的功能,既然H5已经有相关的接口且兼容性良好,当然优先考虑用H5来实现。

前端使用js读取文件操作

首先我们定义一个input标签type=file、然后我们定义一个jsReadFiles的方法将文件作为参数;当上传文件的时候读取这个文件。图片上传成功,只是图片路径变成了base64编码的形式。

HTML5实现文件读取、编辑、保存

HTML5读取文件主要利用的就是FileReader这个API,它的使用需要从一个构造函数开始,保存文件的关键是生成文件对象,可以使用URL.createObjectURL()方法实现,该方法能返回给定对象的URL,用在<a>标签的href属性上就可以创建可下载的文件链接。

血淋淋的事实告诉你:你为什么不应该在JS文件中保存敏感信息

在JavaScript文件中存储敏感数据,不仅是一种错误的实践方式,而且还是一种非常危险的行为,长期以来大家都知道这一点。

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

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

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

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

lock文件_我们为什么需要 lock 文件

从 Yarn 横空出世推出 lock 文件以来,已经两年多时间了,npm 也在 5.0 版本加入了类似的功能,lock 文件越来越被开发者们接收和认可。本篇文章想从前端视角探讨一下我们为什么需要 lock 文件,以及它的一些成本与风险,当然其中一些观点对于后端也是适用的

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

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

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

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

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

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

点击更多...

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