📜  Express如何实现文件上传和下载?

📅  最后修改于: 2022-05-13 01:56:26.617000             🧑  作者: Mango

Express如何实现文件上传和下载?

文件上传和下载是 Web 应用程序的重要功能。这里我们将使用express-fileupload npm 包处理文件上传,并使用 express 的res.download()函数处理下载。 express-fileupload作为中间件传递给应用程序。

方法:首先,安装 express-fileupload 模块,然后将其作为中间件传递给应用程序,如下所示:

const fileUpload = require('express-fileupload')
app.use(fileUpload())

然后为了访问 POST 请求中上传的文件,使用:

req.files.

它提供了一些函数和值,例如文件名、mime 类型、数据和大小。它提供了一个重要的mv()函数,用于保存上传的文件。它将上传路径和错误处理函数作为参数。

req.files..mv(, function(err) {
  // statement(s)
})

下载是使用res.download()函数处理的,该函数有两个参数:文件路径和错误处理函数。

res.download( , function(err) {
  // statement(s)
})

上传和下载的实现:

第一步:创建app.js文件、 index.html文件,并使用以下命令初始化项目:

npm init

第 2 步:使用以下命令安装 express 和 express-fileupload:

npm install express
npm install express-fileupload

项目结构:项目结构如下所示。在项目目录中创建一个上传文件夹,并在项目文件夹中创建一个名为 download_gfg.txt 的文件,该文件将被下载。

项目结构

第 3 步:现在让我们首先编写index.html文件。在其中,我们创建了两个表单,一个处理上传的表单有action='/upload' ,一个处理下载的表单有action='/download'

index.html



    
    
    
    Files


    
    
        

Upload Section


                 
            File to be uploaded:               

                     
        
    
            
        

Download Section


                 
                     
    
      


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");
});


第 4 步:现在我们将编写app.js文件。在其中,我们创建了一个POST 路由 - '/upload'来处理上传和GET 路由 - '/download'来处理下载。对于应用程序根目录的 GET 请求,我们发送index.html文件。

应用程序.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/,你会看到如下命令:

输出