/*
* @Author: your name
* @Date: 2021-08-01 19:22:22
* @LastEditTime: 2021-08-01 20:06:32
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \projectsf:\vue\lianxi\xiaomu\eshop-server\routes\upload.js
*/
var express = require('express');
var router = express.Router();
var multer = require('multer');
var fs = require('fs');
var path = require('path');
//使用表单上传
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/uploads/" + year + month + day;
//判断目录是否存在,没有则创建
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, {
recursive: true
});
}
//dir就是上传文件存放的目录
cb(null, dir);
},
//设置文件名称
filename: function(req, file, cb) {
let fileName = file.fieldname + '-' + Date.now() + path.extname(file.originalname);
//fileName就是上传文件的文件名
cb(null, fileName);
}
})
})
// 请求地址 设置返回路径
router.post('/img',upload.single("img") ,function(req,res,next){
let filePaht = req.file.path.replace('public','')
res.json({
path: filePaht
})
})
module.exports = router