代码实例:如何在Node.js中实现文件上传?

2021年3月12日12:58:07 发表评论 606 次浏览

介绍:文件上传意味着用户从客户端计算机请求将文件上传到服务器。例如, 用户可以在Facebook, Instagram等上上传图像, 视频等。

Multer模块的功能:可以使用Multer模块将文件上传到服务器。市场上还有其他模块, 但是在文件上传方面, multer非常受欢迎。 Multer是用于处理multipart / form-data的node.js中间件, 通常用于上传文件。

注意:Multer将仅处理多部分(multipart / form-data)的那些形式。因此, 每当使用multer时, 请确保将多部分形式放置。

介绍:

  1. 它很容易上手, 易于使用。
  2. 它是文件上传的广泛使用和流行的模块。
  3. 用户可以一次上传单个或多个文件。

Multer模块的安装:

你可以访问链接安装multer模块。你可以使用此命令安装此软件包。 npm安装multer

安装multer之后, 你可以使用命令在命令提示符下检查multer版本。 npm版本multer

之后, 你可以仅创建一个文件夹并添加一个文件, 例如index.js, 要运行此文件, 你需要运行以下命令。节点index.js

要求模块:你需要使用这些行在文件中包括multer模块。 var multer = require('multer');

因此, Multer基本上将一个或多个文件对象以及一个主体对象添加到请求对象。 file / files对象包含通过表单上传的所有文件, 并且表单文本字段的所有值都包含在body对象中。这是无论何时提交表格, multer都会绑定数据的方式。

文件名:Signup.ejs

<!DOCTYPE html>
< html >
  
< head >
     < title >FILE UPLOAD DEMO</ title >
</ head >
  
< body >
     < h1 >Single File Upload Demo</ h1 >
   
     < form action = "/uploadProfilePicture" 
       enctype = "multipart/form-data" method = "POST" >
      
         < span >Upload Profile Picture:</ span >  
         < input type = "file" name = "mypic" required/> < br >
         < input type = "submit" value = "submit" > 
     </ form >
</ body >
  
</ html >

文件名:index.js

const express = require( "express" )
const path = require( "path" )
const multer = require( "multer" )
const app = express()
    
// View Engine Setup
app.set( "views" , path.join(__dirname, "views" ))
app.set( "view engine" , "ejs" )
    
// var upload = multer({ dest: "Upload_folder_name" })
// If you do not want to use diskStorage then uncomment it
    
var storage = multer.diskStorage({
     destination: function (req, file, cb) {
  
         // Uploads is the Upload_folder_name
         cb( null , "uploads" )
     }, filename: function (req, file, cb) {
       cb( null , file.fieldname + "-" + Date.now()+ ".jpg" )
     }
   })
       
// Define the maximum size for uploading
// picture i.e. 1 MB. it is optional
const maxSize = 1 * 1000 * 1000;
    
var upload = multer({ 
     storage: storage, limits: { fileSize: maxSize }, fileFilter: function (req, file, cb){
    
         // Set the filetypes, it is optional
         var filetypes = /jpeg|jpg|png/;
         var mimetype = filetypes.test(file.mimetype);
  
         var extname = filetypes.test(path.extname(
                     file.originalname).toLowerCase());
        
         if (mimetype && extname) {
             return cb( null , true );
         }
      
         cb( "Error: File upload only supports the "
                 + "following filetypes - " + filetypes);
       } 
  
// mypic is the name of file attribute
}).single( "mypic" );       
  
app.get( "/" , function (req, res){
     res.render( "Signup" );
})
    
app.post( "/uploadProfilePicture" , function (req, res, next) {
        
     // Error MiddleWare for multer file upload, so if any
     // error occurs, the image would not be uploaded!
     upload(req, res, function (err) {
  
         if (err) {
  
             // ERROR occured (here it can be occured due
             // to uploading image of size greater than
             // 1MB or uploading different file type)
             res.send(err)
         }
         else {
  
             // SUCCESS, image successfully uploaded
             res.send( "Success, Image uploaded!" )
         }
     })
})
    
// Take any port number of your choice which
// is not taken by any other process
app.listen(8080, function (error) {
     if (error) throw error
         console.log( "Server created Successfully on PORT 8080" )
})

运行程序的步骤:

项目结构将如下所示:

项目结构

这里的"上传"是我们的文件将被上传到的文件夹, 当前为空。 " Singup.ejs"保留在views文件夹中。

确保你拥有像我使用过" ejs"一样的"视图引擎", 并使用以下命令安装express和multer:npm install ejs npm install express npm install multer

使用以下命令运行index.js文件:

node index.js
上面命令的输出

打开浏览器, 然后输入以下URL:http:// localhost:8080 /

然后, 你将看到Singup表单, 如下所示:

这是用于上传单张图片的示例表单

然后选择要上传的文件, 然后单击提交按钮。

如果发生错误, 将显示以下消息:

错误信息

如果没有错误发生, 那么将显示以下消息:

成功讯息

如果文件上传过程成功, 那么你可以转到uploads文件夹并查看你上传的图像, 如下所示:

上传的图片

因此, 这是使用multer模块在Node.js中上传文件的方式。市场上还有其他文件上传模块, 例如文件上传, 快速文件上传等等


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: