Nodejs Advanced: A file upload instance based on Express+multer _node.js

Source: Internet
Author: User
Tags file upload save file

Overview

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

Common open source components are multer, formidable, and so on, with these two open source components, you can easily handle the image upload.

This article mainly explains the following content, subsequent chapters will be in-depth excavation of the technical implementation details.

    • Basic example: the use of Express, multer to achieve Dantu, multiple graphics upload.
    • Common APIs: Get information on uploaded pictures.
    • Advanced use: Customize the saved picture path, name.

Environment initialization

Very simple, one line command.

NPM Install Express Multer multer--save

Below each example, there are two files

➜upload-custom-filename git: (master) ✗tree-l 1
.
├──app.js # Service-side code, used to process file upload requests
├──form.html # front page, used to upload files

Basic example: Single map upload

App.js.

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

var app = Express ();
var upload = Multer ({dest: ' upload/'});

Single map 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" >
   
 

Run the service.

Node App.js

Visit Http://127.0.0.1:3000/form, select Pictures, click "Submit", done. Then you'll see a picture of the upload directory.

Basic example: multi-image upload

Code simply can not be simpler, the front of the Upload.single (' logo ') changed to Upload.array (' logo ', 2) on the line. Says: Supports 2 picture uploads 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/'});

Multiple maps 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" >
  
var fs = require (' FS ');
var express = require (' Express ');
var multer = require (' multer ')

var app = Express ();
var upload = Multer ({dest: ' upload/'});

Single map 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 filename:%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" >
   
 

Start the service, after uploading the file, you will see the information printed under the console.

File type: image/png
Original filename: 1.png
File Size: 18379
File Save path: Upload/b7e4bb22375695d92689e45b551873d9

Custom file upload path, name

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

Customizing a locally saved path

Very simple, for example, we want to upload files to the My-upload directory, modify the Dest configuration items on the line.

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

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

Customizing the locally saved file name

The code is a little bit longer, just as simple as this one. Multer provides storage this parameter to personalize resource-saved paths and file names.

Usage considerations are as follows:

    • Destination: Sets the save path for the resource. Note that if you do not have this configuration item, the default is saved under/tmp/uploads. In addition, the path needs to be created itself.
    • FileName: Sets the file name for the resource to be 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); Custom var storage = Multer.diskstorage ({destination:function (req, file, CB) {CB (NULL, Uploadfolder  ); Saved path, note: Need to create yourself}, Filename:function (req, file, CB) {//Set Save file name to field name + timestamp, such as logo-1478521468943 CB (NUL 
  L, File.fieldname + '-' + Date.now ());

}
}); Customizing the upload behavior via the storage option var upload = Multer ({storage:storage})//Dantu 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" >
   
 

The test steps do not repeat, the visit will know the effect.

It's written in the back.

This paper introduces the basic usage of multer, and does not involve too much original reason. As the saying goes, teach people to fish than to teach people to fish, in the following chapters, will upload the details of the file mining, so that readers to upload a friend to deepen the understanding of the file.
RELATED LINKS

Multer Official Document: Https://github.com/expressjs/multer

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.