如何使用Express实现文件上传和下载
文件上传和下载是Web应用的重要功能。在这里,我们将使用 express-fileupload npm 包来处理文件上传,并使用 express 的 res.download() 函数来处理下载。 express-fileupload 将作为中间件传递给应用程序。
实现方法: 首先,安装 express-fileupload 模块,然后将其导入并作为中间件传递给应用程序,如下所示:
const fileUpload = require('express-fileupload')
app.use(fileUpload())
然后,要在POST请求中访问已上传的文件,可以使用:
req.files.<uploaded_file_name>
它提供一些函数和值,如文件名、mime类型、数据和大小。它提供了一个重要的 mv() 函数,用于保存上传的文件。它以上传路径和错误处理函数作为参数。
req.files.<uploaded_file_name>.mv(<upload_path>, function(err) {
// statement(s)
})
下载使用 res.download() 函数处理,该函数接受两个参数:文件路径和错误处理函数。
res.download( <file_path>, function(err) {
// statement(s)
})
上传和下载的实现:
步骤1: 创建一个 app.js 文件, index.html 文件,并使用以下命令初始化项目:
npm init
步骤2: 使用以下命令安装express和express-fileupload:
npm install express
npm install express-fileupload
项目结构: 项目结构将如下所示。在项目目录下创建一个名为upload的文件夹,并在项目文件夹内创建一个名为download_gfg.txt的文件,该文件将被下载。
步骤3: 现在我们首先来编写 index.html 文件。在其中,我们创建了两个表单,一个处理上传,具有 action=’/upload’ ,另一个处理下载,具有 action=’/download’ 。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible"
content="IE=edge">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Files</title>
</head>
<body>
<!-- Upload section-->
<div>
<h3>Upload Section</h3> <br>
<!-- action to the /upload route-->
<form action="/upload"
method="post"
enctype="multipart/form-data">
File to be uploaded: <input type="file"
name="uploadFile"
id="">
<br><br>
<button type="submit">Upload</button>
</form>
<br>
</div>
<!-- Download Section-->
<div>
<h3>Download Section</h3> <br>
<!-- action to the /download route-->
<form action="/download" method="get">
<button type="submit">Download</button>
</form>
</div>
</body>
</html>
步骤4: 现在我们将编写 app.js 文件。在其中,我们创建了一个 POST 路由 – ‘/upload’ 来处理上传,并且创建了一个 GET 路由 – ‘/download’ 来处理下载。对于应用程序的根目录的 GET 请求,我们发送 index.html 文件。
app.js
// Requiring express to handle routing
const express = require("express");
// The fileUpload npm package for handling
// file upload functionality
const fileUpload = require("express-fileupload");
// Creating app
const app = express();
// Passing fileUpload as a middleware
app.use(fileUpload());
// For handling the upload request
app.post("/upload", function (req, res) {
// When a file has been uploaded
if (req.files && Object.keys(req.files).length !== 0) {
// Uploaded path
const uploadedFile = req.files.uploadFile;
// Logging uploading file
console.log(uploadedFile);
// Upload path
const uploadPath = __dirname
+ "/uploads/" + uploadedFile.name;
// To save the file using mv() function
uploadedFile.mv(uploadPath, function (err) {
if (err) {
console.log(err);
res.send("Failed !!");
} else res.send("Successfully Uploaded !!");
});
} else res.send("No file uploaded !!");
});
// To handle the download file request
app.get("/download", function (req, res) {
// The res.download() talking file path to be downloaded
res.download(__dirname + "/download_gfg.txt", function (err) {
if (err) {
console.log(err);
}
});
});
// GET request to the root of the app
app.get("/", function (req, res) {
// Sending index.html file as response to the client
res.sendFile(__dirname + "/index.html");
});
// Makes app listen to port 3000
app.listen(3000, function (req, res) {
console.log("Started listening to port 3000");
});
运行应用的步骤: 使用以下命令启动应用程序。
node app.js
输出: 打开浏览器,然后转到 **http://localhost:3000/, ** 您将会看到以下命令:

极客教程