Nodejs advanced: File Upload instance based on express + multer

Source: Internet
Author: User
Nodejs advanced: Overview of File Upload instances based on express + multer

Image uploading is a frequently used function in web development. The node community also provides comprehensive support in this regard.

Common open-source components include multer and formidable. With these two open-source components, you can easily upload images.

This article mainly describes the following content. The subsequent sections will explore the technical implementation details in depth.

Basic example: Use express and multer to upload a single or multiple images.

Common APIs: obtain the information of uploaded images.

Advanced usage: Customize the path and name of the saved image.

Environment Initialization

It's very simple, just a line of command.

npm install express multer multer --save

In each example, the following two files are available:

Upload-custom-filename git :( master) upload tree-L 1. ── app. js # server code, used to process File upload requests ── form.html # front-end page, used to upload files

Basic example: Single Image Upload

App. js.

Var fs = require ('fs'); var express = require ('express '); var multer = require ('multer') var app = express (); var upload = multer ({dest: 'upload/'}); // upload the app to a single image. 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 (0, 3000 );

Form.html.

 

Run the service.

Node app. js

Access http: // 127.0.0.1: 3000/form, select an image, click "Submit", done. Then, you will see an additional image under the upload directory.

Basic example: Multi-Image Upload

The Code cannot be simpler. Just change the previous upload. single ('logo ') to upload. array ('logo', 2. Indicates that two images 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/'}); // upload the app to multiple images. 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 (0, 3000 );

Form.html.

 

Do not repeat the same test procedure.

Obtains the information of the uploaded image.

In many cases, in addition to saving images on the server, we also need to do many other things, such as saving image information to the database.

Common Information, such as the original file name, file type, file size, and local storage path. With multer, we can easily obtain this information.

In this example, multer writes 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/'}); // upload the app to a single image. 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 storage 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 (0, 3000 );

Form.html.

 

Start the service. After uploading files, you will see the printed information in the console.

File Type: image/png
Original file name: 1.png
Size: 18379
File Storage path: upload/b7e4bb22375695d92689e45b551873d9

Custom File Upload path and name

Sometimes, we want to customize the File Upload path and name, And multer can also be easily implemented.

Customize Local save path

For example, if you want to upload a file to the my-upload directory, you can modify the dest configuration item.

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

In the preceding configuration, all resources are saved in the same directory. Sometimes we need to customize different files. For details, refer to the content in the next section.

Customize the locally saved file name

The Code is a little longer and simple. Multer provides the storage parameter to customize the path and file name of resource storage.

Note:

Destination: set the path to save the resource. Note: If this configuration item is not available, it will be saved under/tmp/uploads by default. In addition, the path must be created by yourself.

Filename: Specifies the name of the file where the resource is stored 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); // customizes var storage = multer through the filename attribute. 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 file name to field name + timestamp, such as logo-1478521468943 cb (null, file. fieldname + '-' + Date. now () ;}}); // you can use the storage option to customize the upload behavior. var upload = multer ({storage: storage}) // you can upload a single image to the 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 (0, 3000 );

Form.html.

 

If you do not repeat the test steps, you can see the results after accessing them.

Post

This article introduces the basic usage of multer and does not involve too many principles. As the saying goes, it is better to teach people to fish than to teach them to fish. In the subsequent chapters, we will explore the details of File Upload so that readers can better understand file upload.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.