Nodejs file upload based on express+multer

overview

Image upload is a function often used in web development, and the node community also has relatively perfect support in this regard.

Common open source components include multer and formidable. With the help of these two open source components, you can easily upload pictures.

This paper mainly explains the following contents, and the subsequent chapters will dig into the technical implementation details. All examples in this article have code examples, which can be found in here see.

  • Basic example: upload single and multiple images with express and multer.
  • Common API: get the information of uploaded pictures.
  • Advanced use: customize the path and name of the saved picture.

Environment initialization

Very simple, one line command.

npm install express multer multer --save

Under each example, there are the following two files

➜  upload-custom-filename git:(master) ✗ tree -L 1
.
├── app.js # The server code is used to process the file upload request
├── form.html # Front end page for uploading files

Basic example: single image upload

For complete sample code, please refer to here.

app.js.

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

var app = express();
var upload = multer({ dest: 'upload/' });

// Single image upload
app.post('/upload', upload.single('logo'), function(req, res, next){
    res.send({ret_code: '0'});
});

app.get('/form', function(req, res, next){
    var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
    res.send(form);
});

app.listen(3000);

form.html.

<form action="/upload-single" method="post" enctype="multipart/form-data">
    <h2>Single image upload</h2>
    <input type="file" name="logo">
    <input type="submit" value="Submit">
</form>

Run the service.

node app.js

Visit http://127.0.0.1:3000/form , select the picture, click "submit", done. Then, you will see more pictures in the upload directory.

Basic example: multi map upload

For complete sample code, please refer to here.

The code can't be simpler. Upload Change single ('logo ') to upload Array ('logo ', 2) is OK. Indicates that two pictures can be uploaded at the same time, and the name attribute is logo.

app.js.

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

var app = express();
var upload = multer({ dest: 'upload/' });

// Multi map upload
app.post('/upload', upload.array('logo', 2), function(req, res, next){
    res.send({ret_code: '0'});
});

app.get('/form', function(req, res, next){
    var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
    res.send(form);
});

app.listen(3000);

form.html.

<form action="/upload-multi" method="post" enctype="multipart/form-data">
    <h2>Multi map upload</h2>
    <input type="file" name="logo">
    <input type="file" name="logo">
    <input type="submit" value="Submit">
</form>

The same test steps are not repeated.

Get the information of the uploaded picture

For complete sample code, please refer to here.

Many times, in addition to saving the pictures on the server, we also need to do many other things, such as saving the information of the pictures into the database.

Common information, such as original file name, file type, file size, local save path, etc. With the help of multer, we can easily obtain this information.

It is also an example of single file upload. At this time, multer will write the file information to req File, as shown in the following code.

app.js.

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

var app = express();
var upload = multer({ dest: 'upload/' });

// Single image upload
app.post('/upload', upload.single('logo'), function(req, res, next){
    var file = req.file;

    console.log('File type:%s', file.mimetype);
    console.log('Original file name:%s', file.originalname);
    console.log('File size:%s', file.size);
    console.log('File save path:%s', file.path);

    res.send({ret_code: '0'});
});

app.get('/form', function(req, res, next){
    var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
    res.send(form);
});

app.listen(3000);

form.html.

<form action="/upload" method="post" enctype="multipart/form-data">
    <h2>Single image upload</h2>
    <input type="file" name="logo">
    <input type="submit" value="Submit">
</form>

After starting the service and uploading the file, you will see the information printed under the console.

File type: image/png
 Original file name: 1.png
 File size: 18379
 File save path: upload/b7e4bb22375695d92689e45b551873d9

User defined file upload path and name

Sometimes, we want to customize the path and name of file upload, and multer can also be easily implemented.

Customize local saved path

It's very simple. For example, if we want to upload the file to the my upload directory, just modify the dest configuration item.

var upload = multer({ dest: 'upload/' });

Under the above configuration, all resources are saved in the same directory. Sometimes we need to personalize different files, so you can refer to the next section.

Customize the file name saved locally

For complete sample code, please refer to here.

The code is a little longer and the single is just as simple. multer provides the {storage} parameter to personalize the path and file name of resource storage.

Precautions for use are as follows:

  • destination: sets the save path of the resource. Note that if there is no such configuration item, it will be saved in / tmp/uploads by default. In addition, the path needs to be created by yourself.
  • filename: set the file name of the resource saved locally.

app.js.

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

var app = express();

var createFolder = function(folder){
    try{
        fs.accessSync(folder); 
    }catch(e){
        fs.mkdirSync(folder);
    }  
};

var uploadFolder = './upload/';

createFolder(uploadFolder);

// Customization through filename attribute
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadFolder);    // Save the path. Note: you need to create it yourself
    },
    filename: function (req, file, cb) {
        // Set the save file name to field name + timestamp, such as logo-1478521468943
        cb(null, file.fieldname + '-' + Date.now());  
    }
});

// The upload behavior is customized through the storage option
var upload = multer({ storage: storage })

// Single image upload
app.post('/upload', upload.single('logo'), function(req, res, next){
    var file = req.file;
    res.send({ret_code: '0'});
});

app.get('/form', function(req, res, next){
    var form = fs.readFileSync('./form.html', {encoding: 'utf8'});
    res.send(form);
});

app.listen(3000);

form.html.

<form action="/upload" method="post" enctype="multipart/form-data">
    <h2>Single image upload</h2>
    <input type="file" name="logo">
    <input type="submit" value="Submit">
</form>

The test steps are not repeated. You can know the effect by visiting.

Write it at the back

This paper introduces the basic usage of multer, and does not involve too many principled things. As the saying goes, it's better to teach people to fish than to teach people to fish. In the subsequent chapters, we will dig into the details of file upload, so that readers can deepen their understanding of file upload.

Related links

Official document of multer: GitHub - expressjs/multer: Node.js middleware for handling `multipart/form-data`.


github blog: GitHub - chyingp/blog: blog of program ape xiaoka
Sina Weibo: Sina Visitor System
Station cool homepage: chyingp's home page - zcool

Classification: Open source library / framework usage and source code analysisGetting started with NODE

Label: nodeexpressmulterfront endPicture upload

Nodejs advanced: file upload based on express+multer - program ape card - blog Garden (cnblogs.com)

Keywords: Javascript node.js Front-end PostMan

Added by Sir Mildred Pierce on Thu, 20 Jan 2022 06:24:04 +0200