nodejs创建服务上传图片
var express = require("express")
var router = express.Router()
var fs = require("fs")
var path = require("path")
var multer = require("multer")
var upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
let date = new Date();
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let day = date.getDate();
let dir = "./public/img/" + year + month + day;
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {
recursive: true
});
}
cb(null, dir);
},
filename: function (req, file, cb) {
let fileName = file.fieldname + '-' + Date.now() + path.extname(file.originalname);
cb(null, fileName);
}
})
})
router.post('/img', upload.single("mainPic"), function (req, res)
{
let file = req.file
let path = file.path.replace('public', "")
res.json({
file: path
})
})
module.exports = router