Home  >  Article  >  Web Front-end  >  Nodejs+express middleware implements file upload

Nodejs+express middleware implements file upload

青灯夜游
青灯夜游forward
2021-04-16 11:00:492300browse

This article will give you a detailed introduction to the Nodejs method of file upload. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Nodejs+express middleware implements file upload

When I use nodejs to do projects, I need to use the file upload function. I searched many tutorials on the Internet and found an express middleware for processing Multipart/form-data type of form data can easily save the file data in the form to the server.

Introduction


multer is a node.js file upload middleware. It is developed on the basis of busboy. The uploaded form data must be multipart/form- data type, otherwise an error will be reported. [Related recommendations: "nodejs tutorial"]

Simple usage


#Define memory

Multer as an intermediate of express file, we can easily customize the uploaded file directory and saved file name. Let’s look at the simplest usage first, demo1 address:

var express = require('express');
var multer = require('multer');
var app = express();

var upload = multer({
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, './uploads/');
        },
        filename: function (req, file, cb) {
            //file.originalname上传文件的原始文件名
            var changedName = (new Date().getTime())+'-'+file.originalname;
            cb(null, changedName);
        }
    })
});

We first create an upload object. The destination function in this object is used to define the folder where the uploaded file is stored; the filename function Used to modify the file name of the uploaded file stored in the server. Here we add a timestamp to simply distinguish it. Both functions are implemented through callback functions. These two functions will be called once for each upload. If multiple files are uploaded, these two functions will be called multiple times. The calling sequence is to call destination first, and then call filename.

There will be a file object in both functions, which represents the currently uploaded file object and has the following attributes:

  • fieldname: uploaded field Name
  • originalname: Uploaded file name
  • encoding: File encoding type
  • mimetype: File MIME type

Attach : Some commonly used MIME types

Define routing callback

//单个文件上传
app.post('/upload/single',upload.single('singleFile'),(req,res)=>{
    console.log(req.file);
    res.json({
        code: '0000',
        type:'single',
        originalname: req.file.originalname
    })
});

//多个文件上传
app.post('/upload/multer',upload.array('multerFile'),(req,res)=>{
    console.log(req.files);
    let fileList = [];
    req.files.map((elem)=>{
        fileList.push({
            originalname: elem.originalname
        })
    });
    res.json({
        code: '0000',
        type:'multer',
        fileList:fileList
    });
});

When defining the routing callback function in express, define it The upload object is added as middleware. If it is a single file, use the single method. If it is multiple files, use the array method. Both methods need to pass a field name defined on the page.

In the routing callback function, the request object already has a file attribute (single file upload) or files attribute (multiple file uploads). The files attribute is an array, and each object in the array has the following attributes. :

  • fieldname: Uploaded field name
  • originalname: Uploaded file name
  • encoding: File encoding type
  • mimetype: File MIME type
  • destination: the stored directory (the same as the directory name in the destination callback function)
  • filename: the saved file name (the same as the file name in the filename callback function)
  • path: The relative path saved
  • size: The size of the file (unit: byte)

We can find that the file object in the routing callback function is larger than diskStorage The file object in has several more attributes. This is because the file has not been saved in diskStorage, and only the general attributes of the file can be known; and the callback function file of the route has been saved on the server, the file's saving path and the file's The sizes are all known.

Mixed upload

Sometimes we may need to use field names to divide the uploaded files, such as uploading multiple images You may have an ID card and a profile picture. Although it can be separated into two interfaces, it will cause a series of other troubles. multer supports dividing images into field names. demo3 address

//多字段名上传
let multipleFields = upload.fields([
    {name:'avatar'},
    {name:'gallery', maxCount:3},
]);
app.post('/upload/fields', (req,res)=>{
    multipleFields(req,res,(err) => {
        console.log(req.files);
        if(!!err){
            console.log(err.message);
            res.json({
                code: '2000',
                type: 'field',
                msg:err.message
            })
            return;
        }
        var fileList = [];
        for(let item in req.files){
            var fieldItem = req.files[item];
            fieldItem.map((elem) => {
                fileList.push({
                    fieldname: elem.fieldname,
                    originalname: elem.originalname
                })
            });
        }
        res.json({
            code: '0000',
            type: 'field',
            fileList: fileList,
            msg:''
        })
    });
});

There is also the req.files attribute here, but this attribute is not an array, but a complex object. There are many Attributes, each attribute name is a field name, and under each attribute is an array. Under the array are file objects. The structure is roughly as follows:

{
    "avatar":[{
        fieldname: "",
        originalname: ""
        //...
    }],
    "gallery":[{
        fieldname: "",
        originalname: ""
        //...
    }]
}

Filter file upload


When uploading files, sometimes some file types we don’t need are uploaded, and we need to filter out some unnecessary files. demo2 address.

File type filtering

var upload = multer({
    //...其他代码
    fileFilter: function(req, file, cb){
        if(file.mimetype == 'image/png'){
            cb(null, true)
        } else {
            cb(null, false)
        }
    }
});

When defining the memory, add a fileFilter function to filter out what we don’t need file, in the callback function we pass true/false to indicate whether to save it; if false is passed, the destination function and filename function will not be called.

文件大小和数量过滤

var upload = multer({
    //...其他代码
    limits:{
        //限制文件大小10kb
        fileSize: 10*1000,
        //限制文件数量
        files: 5
    }
});

在定义存储器的时候,新增一个limits对象,用来控制上传的一些信息,它有以下一些属性:

  • fieldNameSize:field 名字最大长度,默认值:100 bytes
  • fieldSize:field 值的最大长度,默认值:1MB
  • fields:非文件 field 的最大数量
  • fileSize:在multipart表单中, 文件最大长度 (字节单位)
  • files:在multipart表单中, 文件最大数量
  • parts:在multipart表单中, part传输的最大数量(fields + files)

在这边我们把fileSize的值设置得小一点,设为10kb方便测试看效果,但是如果这个时候会发现有报错。因为上传的文件大小很容易就会超过10KB,导致有报错出现,我们就需要在路由回调里对错误的情况进行捕获。

//单个文件上传
let singleUpload = upload.single('singleFile');
app.post('/upload/single',(req,res)=>{
    singleUpload(req,res,(err)=>{
        if(!!err){
            console.log(err.message)
            res.json({
                code: '2000',
                type:'single',
                originalname: '',
                msg: err.message
            })
            return;
        }
        if(!!req.file){
            res.json({
                code: '0000',
                type:'single',
                originalname: req.file.originalname,
                msg: ''
            })
        } else {
            res.json({
                code: '1000',
                type:'single',
                originalname: '',
                msg: ''
            })
        }
    });
});

//多个文件上传
let multerUpload = upload.array('multerFile');
app.post('/upload/multer', (req,res)=>{
    multerUpload(req,res,(err)=>{
        if(!!err){
            res.json({
                code: '2000',
                type:'multer',
                fileList:[],
                msg: err.message
            });
        }
        let fileList = [];
        req.files.map((elem)=>{
            fileList.push({
                originalname: elem.originalname
            })
        });
        res.json({
            code: '0000',
            type:'multer',
            fileList:fileList,
            msg:''
        });
    });
});

所有的demo代码都在仓库里,地址:https://github.com/acexyf/multerDemo

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Nodejs+express middleware implements file upload. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete