Home > Web Front-end > JS Tutorial > body text

Implementing file upload function based on nodejs express(4.x)_node.js

WBOY
Release: 2016-05-16 15:30:39
Original
1484 people have browsed it

Nodejs is a young programming framework, full of vitality and unlimited passion, and has always been updated rapidly. Express, the official web development library based on Nodejs, is also developing simultaneously, with a major version upgrade every year and even major surgery on the bottom layer of the framework. In Express4, the middleware library connect was replaced by multiple more fine-grained libraries. The obvious benefit is that these middleware can be updated and released more freely and will not be affected by the Express release cycle; but the problem is also very difficult. It is not compatible with previous versions, and upgrading means modifying the code.

After a period of research and exploration, I found that the ways to achieve uploading are: 1. express middleware multer module (this is the most efficient, natively supported in express3.x, and became an independent module in express4.x), 2. connect-multiparty module (but it is not officially recommended now), 3. Use the multiparty module to implement (this method is more common), 4. Use the formidable plug-in to implement (the plug-in is simple and easy to understand);

The simplest way is to upload through the "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 when done 
});
Copy after login

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

Just move and rename the temporary file to the actual directory in the commented place to complete the upload function.

Simple.

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

However, the official does not recommend using this middleware. It is recommended to use "multiparty" directly because error handling is more troublesome.

Let’s use “multiparty” to implement a version.

1. Use express (version 4.11.x) to create a project, using the default jade as the template engine.

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

3. Modify views/index.jade and make a simple form for file upload as follows.

 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='上传')
Copy after login

4. Modify routes/index.js to implement the background code for uploading pages and uploading responses.

 var express = require('express');                                                                                                                      
  var router = express.Router();
  var multiparty = require('multiparty');
  var util = require('util');
  var fs = require('fs');
  /* 上传页面 */
  router.get('/', function(req, res, next) {
   res.render('index', { title: 'Express' });
 });
 /* 上传*/
 router.post('/file/uploading', function(req, res, next){
  //生成multiparty对象,并配置上传目标路径
  var form = new multiparty.Form({uploadDir: './public/files/'});
  //上传完成后处理
  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;
    //重命名为真实文件名
    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;
Copy after login

Done. This completes the introduction to the file upload function based on nodejs express (4.x). I hope it will be helpful for everyone to learn nodejs express related knowledge.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template