Express + multer realizes file upload function

beginning

 

var express = require('express');
const multer = require('multer');
const upload = multer({dest:"/xlsx/"});        //这里的路径可以随便写

 

Then let's write the front-end single file upload function

 

<html>
<meta charset="UTF-8">
<head>
<title>文件上传表单</title>
</head>
<body align="center">
选择一个文件上传: <br /><br />
<form action="http://localhost:3000/api/single" method="post" enctype="multipart/form-data">

<input type="file" name="image" size="50" /><br /><br />

<input type="submit" value="上传文件" />
</form>
</body>
</html>

 

The back end of the node, upload.single('image') where "image" must correspond to the name of the front end, otherwise it will not be received

 

router.post('/api/single',upload.single('image'),function (req,res,next) {        //单文件上传
  fs.readFile(req.file.path,function (err,data) {
    fs.writeFile('./public/image/' + new Date().getTime() + req.file.originalname,data,function (err) {
      if(err)throw err;
    })
  });
  res.send(req.file.originalname);
  res.end();
});

 

Next, demonstrate the multi-file upload front end

 

<html>
<meta charset="UTF-8">
<head>
<title>文件上传表单</title>
</head>
<body align="center">
选择一个文件上传: <br /><br />
<form action="http://localhost:3000/api/many" method="post" enctype="multipart/form-data">

<input type="file" name="image" size="50" /><br /><br />

<input type="file" name="image" size="50" /><br /><br />

<input type="submit" value="上传文件" />
</form>
</body>
</html>

 

 

Node's backend code

 

router.post('/api/many',upload.array('image'),function (req,res,next) {        //多文件上传
  let files = req.files;
  files.map((v)=>{
    fs.readFile(v.path,function (err,data) {
      fs.writeFile('./public/image/' + new Date().getTime() + v.originalname,data,function (err) {
        if(err)throw err;
      })
    });
  });
  res.send(req.files);
  res.end();
});

 

When taking the variable name, do not write the variable name as value, otherwise it will not be traversed.

If you encounter the problem of garbled reading of Chinese file names, use Nodepad++ to see the encoding of the source code and convert it to UTF-8.

Guess you like

Origin blog.csdn.net/u012149637/article/details/88710219