Implement the file upload function based on nodejs + express (4.x+) _ node. js

Source: Internet
Author: User
Tags parse error
After reading the data for a period of time, we found that the upload methods are as follows: 1. express middleware multer Module 2. connect-multiparty module (but not officially recommended) 3. use the multiparty module. 4. using the formidable plug-in, this article introduces nodejs + express (4.x+) to implement the file upload function. For more information, see Nodejs as a young programming framework, fast updates are always maintained. Express, the official Web development library based on Nodejs, is also developing. It upgrades a large version every year and even performs major operations on the underlying framework. In Express4, replace the inter-component database connect, instead of multiple finer-grained databases. The advantage is that these middleware can be updated and released more freely without being affected by the Express release cycle. However, the problem is also very tricky and incompatible with previous versions, upgrading means modifying the code.

After a period of Data Reading and exploration, I found that the upload methods are as follows: 1. express middleware multer module (this is the most efficient. It is supported by express3.x native and express4.x is an independent module), 2. connect-multiparty module (but not officially recommended), 3. implementation using the multiparty module (this method is common), 4. use the formidable plug-in (the plug-in is easy to understand );

The simplest way is to upload through the connect-multiparty middleware.

Install 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 });

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

You only need to move the temporary file in the comments and rename it to the actual directory to complete the upload function.

Simple.

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

However, we do not recommend using this middleware officially. We recommend that you use "multiparty" directly because it is troublesome to handle errors.

Next we will use "multiparty" to implement a version.

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

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

3. Modify views/index. jade to make a simple form for file upload.

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

4. Modify routes/index. js to upload the page and background code of the response.

Var express = require ('express '); var router = express. router (); var multiparty = require ('multipart'); 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 a multiparty object and configure the upload Destination path var form = new multiparty. form ({uploadDir :'. /public/files/'}); // form after the upload is complete. 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 it to the real file name 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 ('stored ed upload: \ n \ n'); res. end (util. inspect ({fields: fields, files: filesTmp}) ;}); module. exports = router;

Complete. All the File Upload functions based on nodejs + express (4.x+) are described. I hope you can learn about nodejs express.

Related Article

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.