const multer = require('koa-multer');
const fs = require('fs');
const path = require('path');

// 设置文件存储位置和上传大小限制
let storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let dir = "./public/uploads/" + 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);
  },
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB的文件大小限制
  },
});

// 上传图片接口
router.post("/img", upload.single("file"), async (ctx) => {
  let path = ctx.req.file.path;
  path = ctx.origin + "" + path.replace("public", "");
  path = path.replace(/\\/g, "/");
  console.log(path);

  ctx.body = path;
});

// 错误处理程序
app.use((ctx, next) => {
  return next().catch((err) => {
    if (err.name === "MulterError") {
      ctx.status = 400; // 设置响应状态码为400，表示请求错误
      ctx.body = "文件大小超过限制"; // 返回给客户端的提示信息
    } else {
      throw err;
    }
  });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});