


Implementing file upload function based on nodejs express(4.x)_node.js
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 });
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='上传')
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;
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

Express and Laravel are two very popular web frameworks, representing the excellent frameworks of the two major development languages of JavaScript and PHP respectively. This article will conduct a comparative analysis of these two frameworks to help developers choose a framework that is more suitable for their project needs. 1. Framework Introduction Express is a web application framework based on the Node.js platform. It provides a series of powerful functions and tools that enable developers to quickly build high-performance web applications. Express

In-depth comparison of Express and Laravel: How to choose the best framework? When choosing a back-end framework suitable for your project, Express and Laravel are undoubtedly two popular choices among developers. Express is a lightweight framework based on Node.js, while Laravel is a popular framework based on PHP. This article will provide an in-depth comparison of the advantages and disadvantages of these two frameworks and provide specific code examples to help developers choose the framework that best suits their needs. Performance and scalabilityExpr

How does node+express operate cookies? The following article will introduce to you how to use node to operate cookies. I hope it will be helpful to you!

Express vs. Laravel: Comparing the advantages and disadvantages, which one will you choose? In the field of web development, Express and Laravel are two frameworks that have attracted much attention. Express is a flexible and lightweight web application framework based on Node.js, while Laravel is an elegant and feature-rich web development framework based on PHP. This article will compare the advantages and disadvantages of Express and Laravel in terms of functionality, ease of use, scalability, and community support, and combine

How to use React and Express to build a full-stack JavaScript application Introduction: React and Express are currently very popular JavaScript frameworks. They are used to build front-end and back-end applications respectively. This article will introduce how to use React and Express to build a full-stack JavaScript application. We will explain step by step how to build a simple TodoList application and provide specific code examples. 1. Preparation before starting

When it comes to choosing a backend framework, both Express and Laravel are very popular choices. Express is a web application development framework based on Node.js, while Laravel is a web application development framework based on PHP. Both have their own advantages, and choosing the framework that best suits you requires considering many factors. The strengths of the Express framework are its flexibility and easy learning curve. The core idea of Express is "small enough and flexible enough", and it provides a large number of middleware

How to use Node.js to build a simple blog system Node.js is a JavaScript runtime environment based on the ChromeV8 engine, which can make JavaScript run more efficiently. With the help of Node.js, we can build powerful server-side applications using JavaScript, including blogging systems. This article will introduce you to how to use Node.js to build a simple blog system and provide you with specific code examples. Press
