search
HomeWeb Front-endJS TutorialNodejs+express middleware implements file upload

Nodejs+express middleware implements file upload

Apr 16, 2021 am 11:00 AM
nodejsFile Upload

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:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.