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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool