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.
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();
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)
(c)npm install express multer
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);
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('f1'));
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>
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('http'); var fs = require('fs'); var path = require('path'); var server = http.createServer(function (req, res) { var method = req.method; // 获取请求方法 if (method === 'POST') { // 暂只关注 post 请求 var dataStr = ''; req.on('data', function (chunk) { // 接收到数据,先存储起来 var chunkStr = chunk.toString() dataStr += chunkStr }); req.on('end', function () { // 接收数据完成,将数据写入文件 var fileName = path.resolve(__dirname, 'post.txt'); fs.writeFile(fileName, dataStr) res.end('OK'); }); } }); server.listen(8081);
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!