File upload function based on nodejs+express (4.x+) _node.js

Source: Internet
Author: User
Tags error handling file upload parse error

Nodejs is a young programming framework, full of energy and unlimited passion, has been keeping the fast update. The official web Development Library, based on Nodejs, is also developing at the same pace, upgrading a large version every year, and even doing major operations on the bottom of the frame. In the EXPRESS4, replace the middle part of the library connect, instead of using a number of finer-grained libraries to replace. The benefit is obviously that these middleware can be more free to update and release, will not be affected by the express release cycle, but the problem is also very difficult, incompatible with the previous version, upgrade means to modify the code.

Through a period of access to information, groping, I found that the way to upload is: 1.express middleware Multer Module (this is the highest efficiency, in express3.x native support, to the express4.x independent into a module), 2.connect-multiparty module (but now officially not recommended), 3. Using the Multiparty module implementation (this method is more common), 4. Use the formidable plug-in implementation (plug-in, it is easy to understand);

The simplest approach is to upload via "connect-multiparty" middleware.

Install by NPM install Connect-multiparty in the project.

Usage:

var multipart = require (' Connect-multiparty ');
var multipartmiddleware = multipart ();
App.post ('/upload ', multipartmiddleware, function (req, resp) {
 console.log (req.body, req.files);
 Don ' t forget to delete all req.files as done 
});

After uploading, the uploaded file will generate a temporary file in the temporary directory, which can print out the req.files to view the specific file path.

The upload function can be completed as long as the temporary files are moved and renamed to the actual directory at the point of comment.

Simple.

Official address: Https://www.npmjs.com/package/connect-multiparty

However, the official does not recommend the use of the middleware, the proposed direct use of "multiparty", because error handling is more cumbersome.

Here's how to implement a version with "multiparty".

1. Use Express (version is 4.11.x) to create a project, using the default Jade as a template engine.

2. In the project directory, install the necessary components through the NPM install multiparty.

3. Modify the Views/index.jade, such as the following to make a simple file upload form.

 Extends layout block
  content                       form (method= ' post ', action= '/file/uploading ', enctype= ' Multipart/form-data ')
    input (name= ' inputfile ', type= ' file ', multiple= ' mutiple ')
    input (name= ' btnup ', type= ' submit ', value= ' upload ')

4. Modify the Routes/index.js, implement the upload page and upload the response background code.

 var express = require (' Express '); var router = Express.
  Router ();
  var multiparty = require (' multiparty ');
  var util = require (' util ');
  var fs = require (' FS ');
 /* Upload page */router.get ('/', function (req, res, next) {Res.render (' index ', {title: ' Express '});
 }); /* Upload/router.post ('/file/uploading ', function (req, res, next) {//Generate multiparty object, and configure the upload target path var form = new Multiparty .
  Form ({uploaddir: './public/files/'});
   Post-upload completes processing form.parse (req, Function (Err, fields, files) {var filestmp = json.stringify (Files,null,);
   if (err) {console.log (' Parse error: ' + err);
    else {console.log (' Parse files: ' + filestmp);
    var inputfile = files.inputfile[];
    var uploadedpath = Inputfile.path;
    var dstpath = './public/files/' + inputfile.originalfilename;
Rename to True filename fs.rename (uploadedpath, Dstpath, function (err) {if (err) {      Console.log (' Rename error: ' + err);
     else {console.log (' rename ok ');
   }
    });
   } res.writehead (, {' Content-type ': ' text/plain;charset=utf-'});
   Res.write (' received upload:\n\n ');
  Res.end (Util.inspect ({fields:fields, files:filestmp}));
 });
 }); Module.exports = router;

Complete. Based on nodejs+express (4.x+) Implementation of the file upload function is all introduced, I hope to learn Nodejs Express related knowledge to help.

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.