multer实现图片上传:
ejs代码:
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>图片上传</title>
</head> <body>
<!--
在终端安装:cnpm install multer
Multer是nodejs中处理multipart/form-data数据格式(主要用在上传功能中)的中间件。该中间件不处理multipart/form-data数据格式以外的任何形式的数据 -->
<!-- 单张上传 -->
<h3>单张上传</h3>
<form action="/uploadImg/addimg" method="post" enctype="multipart/form-data">
<input type="file" name="img" id="img1">
<input type="submit" value="提交">
</form> <!-- 多张上传 -->
<h3>多张上传</h3>
<form action="/uploadImg/addimgs" method="post" enctype="multipart/form-data">
<input type="file" name="imgs" multiple id="img2">
<input type="submit" value="提交">
</form> <!-- ajax单张上传图片 -->
<h3>ajax单张上传图片</h3>
<input type="file" name="ajaximg" id="ajaximg">
<input type="submit" value="提交" id="ajaxbtn"> <!-- ajax多张上传图片 -->
<h3>ajax多张上传图片</h3>
<input type="file" name="ajaximg" multiple id="ajaximgs">
<input type="submit" value="提交" id="ajaxbtns">
</body>
<script src="web/js/jquery-1.10.1.min.js"></script>
<script>
// ajax单张上传
$("#ajaxbtn").click(function (e) {
// console.log($("#ajaximgs")[0].file[0])
let file = $("#ajaximg")[0].files[0];
let formdata = new FormData();
formdata.append("img", file);
// ajax单张上传
$.ajax({
type: "POST",//默认post
url: "/uploadImg/addimg",//默认当前页
data: formdata,//格式(key:value)
contentType: false,
processData: false,
dataType: "json",
beforeSend: function () { },//请求发送当前回调,常用验证
success: function (response) {//请求成功回调
alert("上传成功");
},
error: function (e) {
if (e.statusText == "timeout") {
alert("请求成功"); }
},
// 请求成功与否都会执行的回调
complete: function () { }
});
}); // ajax多张上传
$("#ajaxbtns").click(function (e) {
// console.log($("#ajaximgs")[0].files)
let files = $("#ajaximgs")[0].files;
let formdata = new FormData();
for (const file of files) {
formdata.append("imgs", file);
}
// ajax单张上传
$.ajax({
type: "POST",//默认post
url: "/uploadImg/addimgs",//默认当前页
data: formdata,//格式(key:value)
contentType: false,
processData: false,
dataType: "json",
beforeSend: function () { },//请求发送当前回调,常用验证
success: function (response) {//请求成功回调
alert("上传成功");
},
error: function (e) {
if (e.statusText == "timeout") {
alert("请求成功"); }
},
// 请求成功与否都会执行的回调
complete: function () { }
});
});
</script> </html>
服务器代码:
// 引入模块
var express = require('express');
var fs = require("fs");
var router = express.Router();
var multer = require("multer");
// 设置上传图片的文件夹
var upload = multer({ dest: "public/uploads/" }); /* GET home page. */
router.get('/', function (req, res, next) {
res.render("phone/uploadImg");
});
// .single(fieldname)
// 该方法接收单个上传的文件 fieldname为上传文件所用的标签name属性。上传的文件信息存储在req.file中
// 单张上传
router.post('/addimg', upload.single("img"), function (req, res) {
let file = req.file;
// fieldname: 上传文件标签在表单中的name
let filename = "public/uploads/" + file.filename;
// 判断上传的图片格式
// mimetype:该文件的Mime type
if (file.mimetype == "image/jpeg") {
filename += ".jpg";
}
if (file.mimetype == "image/png") {
filename += ".png";
}
if (file.mimetype == "image/gif") {
filename += ".gif";
}
fs.renameSync(file.path, filename);
console.log(req.file);
// 响应
res.json("上传成功");
}); // 多张图片上传
router.post('/addimgs', upload.array("imgs"), function (req, res) {
let files = req.files; for (let file of files) {
// fieldname: 上传文件标签在表单中的name
let filename = "public/uploads/" + file.filename;
// 判断上传的图片格式
// mimetype:该文件的Mime type
if (file.mimetype == "image/jpeg") {
filename += ".jpg";
}
if (file.mimetype == "image/png") {
filename += ".png";
}
if (file.mimetype == "image/gif") {
filename += ".gif";
}
fs.renameSync(file.path, filename);
}
console.log(req.file);
// 响应
res.json("上传成功");
}); module.exports = router;
路由接口:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// 前端
// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');
// var IndexRouter = require('./routes/phone/index');
// var detailRouter = require('./routes/phone/detail');
// var newsShowRouter = require('./routes/phone/news-show');
// var newsRouter = require('./routes/phone/news');
// var otherListRouter = require('./routes/phone/other-list');
// var proListRouter = require('./routes/phone/pro-list');
// var tableRouter = require('./routes/phone/table');
var uploadImgRouter = require('./routes/phone/uploadImg');//图片上传路由 // 后台
var adminRouter = require('./routes/admin/index');
var adminMainRouter = require('./routes/admin/pages/main');
var adminDelRouter = require('./routes/admin/pages/article/del');
var adminIndexRouter = require('./routes/admin/pages/article/index');
var adminEditRouter = require('./routes/admin/pages/article/edit'); var app = express(); // view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser()); // 设置public为局部变量
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
// app.use('/users', usersRouter);
// app.use('/index', IndexRouter);
// app.use('/detail', detailRouter);
// app.use('/newsShow', newsShowRouter);
// app.use('/news', newsRouter);
// app.use('/other', otherListRouter);
// app.use('/pro', proListRouter);
// app.use('/table', tableRouter);
app.use('/uploadImg', uploadImgRouter); // 后台
// app.use('/admins', adminRouter);
// app.use('/adminMain', adminMainRouter);
// app.use('/adminDel', adminDelRouter);
// app.use('/adminindex', adminIndexRouter);
// app.use('/adminEdit', adminEditRouter); // catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
}); // error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page
res.status(err.status || 500);
res.render('error');
}); module.exports = app;