nodejs多图上传(有接受单图,多图,base64的例子)

先下载multer

yarn add multer

单图加上多图上传
【nodejs多图上传(有接受单图,多图,base64的例子)】引入了multer之后,就直接在req上挂载了1个file对象,这里注意区别,服务器接受单图,对象在req.file里面,接受多图就在req.files里面,还有下面的方法,upload.array()方法file是前端传递的key,后面的参数是一次最多接受多少张图片,
如果只接受单图请upload.fields('file')即可
const express = require('express') var fs = require("fs")//操作文件 var multer = require('multer') const upload = multer({dest: 'upload/'}) // 拿到express路由 const Router = express.Router() Router.post('/upload', upload.array('file', 2), function (req, res, next) { var file = req.files var arrPath = [] for (var i = 0; i < file.length; i++) { var pathName = "upload/" + file[i].filename + '.' + file[i].originalname.split('.')[1] fs.rename(req.files[i].path, pathName, function (err) { if (err) { throw err; } }) arrPath.push({path: pathName}) } res.json({code: 0, data: arrPath}) })

后端接受前端的base64转换成图片保存在服务器
这里需要注意的是:base是文本依赖于body-parser
yarn add body-parser // 接受post过来的json,最大为50m,预防前端传递base64图片 app.use(bodyParser.json({limit: '50mb'}))

Router.post('/uploadbase', upload.fields('file'), function (req, res, next) { var file = req.body.file var base64Data = file.replace(/^data:image\/\w+; base64,/, '') var dataBuffer = new Buffer(base64Data, 'base64') var path = './upload/' + Math.random().toString().split('.')[1] + Date.now() + '.jpg' fs.writeFile(path, dataBuffer, function (err) { if (err) return res.json({code: 0, data: {path: path}, msg: '图片上传成功'}) }) })

    推荐阅读