Home > Web Front-end > JS Tutorial > node.js uses multer middleware to upload files

node.js uses multer middleware to upload files

青灯夜游
Release: 2021-03-04 10:36:16
forward
1858 people have browsed it

This article will introduce to you how node.js uses multer middleware to solve the post file upload problem. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

node.js uses multer middleware to upload files

Related recommendations: "nodejs Tutorial"

body-parser middleware is actually "extremely imperfect" - it only Able to handle "simple data".
As we all know, post is often used for two things:

  • Data submission (post form submission)

  • File upload

But the "famous" body-parser can only do the first thing.

Uncomfortable...

The formidable module was used in the image file upload article I wrote before, and its core lies in:

var form=new formidable.IncomingForm();
Copy after login

The following form.uploadDir, field/end monitoring... are all based on this.

Okay, what we want to talk about here is the disadvantage: like body-parser, the formidable plug-in can only be used to process image formats, which is also a big pity.


So, the author found multer middleware, hoping that it can "save the fragmented mountains and rivers" (haha)

One of the applications of multer middleware :File upload

(c)npm install express multer
Copy after login
const express = require('express');
const bodyparser = require('body-parser');//解析post数据
const multer = require('multer'); //解析Post文件
const fs = require('fs');
const pathlib = require('path'); //解析文件路径
 
var server = express();
 
var objMulter = multer({dest:'./www/upload'}); //用户上传文件存入dest目录下
server.use(objMulter.any()); //处理任何用户上传的文件
 
//处理post文件数据
server.post('/',function(req,res){
	console.log(req.files[0].originalname); //req.files post文件 originalname为文件名
 
	//获取原始拓展名+后缀名
	var newName = req.files[0].path+pathlib.parse(req.files[0].originalname).ext;
 
	//重命名
	fs.rename(req.files[0].path,newName,function(err){
		if(err){
			res.send('上传失败');
		}else{
			res.send('上传成功');
		}
	});
});
server.listen(8081);
Copy after login

Here, req.files is used instead of req.body: Because only (text) numbers can be stored in the body - if you use body-parser here, you will only see the console. Displayed file name.

The function of objMulter.any() in the code is to "get all data";
There is also a single( opposite to any() ), which requires specifying a parameter - the name in the front-end <input>! For example, in this example, you can also write like this:

server.use(objMulter.single(&#39;f1&#39;));
Copy after login

The front-end code is as follows - file submission, the specified format is multipart/form-data:

<form action="http://localhost:8081/" method="post" enctype="multipart/form-data">
	文件:<input type="file" name="f1" /><br />
	<input type="submit" value="上传" />
</form>
Copy after login

In fact It uses the rename (original path, new path, callback) method in the fs module to achieve the purpose of "uploading files" by forcibly changing the storage path of the file.


Today’s expansion:
The resolve method in the path module is commonly used in node to "specify files" (note lines 16/17):

var http = require(&#39;http&#39;);
var fs = require(&#39;fs&#39;);
var path = require(&#39;path&#39;);

var server = http.createServer(function (req, res) {
    var method = req.method; // 获取请求方法
    if (method === &#39;POST&#39;) { // 暂只关注 post 请求
        var dataStr = &#39;&#39;;
        req.on(&#39;data&#39;, function (chunk) {
            // 接收到数据,先存储起来
            var chunkStr = chunk.toString()
            dataStr += chunkStr
        });
        req.on(&#39;end&#39;, function () {
            // 接收数据完成,将数据写入文件
            var fileName = path.resolve(__dirname, &#39;post.txt&#39;);
            fs.writeFile(fileName, dataStr)
            res.end(&#39;OK&#39;);
        });
    }
});
server.listen(8081);
Copy after login

For more programming-related knowledge, please visit: Programming Learning! !

The above is the detailed content of node.js uses multer middleware to upload files. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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