1)利用multer模块以及fs模块保存上传的图片
//index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<from action="http://localhost:5000/upData" method="post" enctype="multipart/form-data">
<input type="flie" name="isUpdata" multiple>
<p></p>
<button>图片提交</button>
</form>
</body>
</html>
//main.js
var express = require('express'),fs = require('fs'),multer = require('multer');
let app = express();
app.use(multer({dest;'/tamp/'}).array('isUpdata')) //注意这里的array的参数就是前台控件的name
app.get('/',(req,res)=>{
res.sendFile(__dirname+'/index.html');
})
app.post('/upData',(req,res)=>{
console.log(req.files) 用户上传的图片信息
var result = req.files;
result.forEach((value)=>{
var newName = value.originalname //这个是图片上传的名字建议加上随机保证图片不会替换
var readStream = fs.createReadStream(value.path);//创建可读流
var writeStrea, = fs.createWriteStream(newName );
readStream.pipe(writeStrea);
console.log(newName +'图片上传成功');
readStream.on('error',()=>{console.log('上传失败')})
})
res.end();//返回信息自己定义
})
- path---文件的临时路径
- mimetype---文件类型
- originalname---文件名称
- size---文件大小