Skip to content
js
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const app = express();

// 动态创建目录
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // 确保是两位数
    const day = String(now.getDate()).padStart(2, '0');

    const uploadPath = path.join(__dirname, 'images', year.toString(), month, day);

    // 如果目录不存在,则递归创建
    fs.mkdirSync(uploadPath, { recursive: true });

    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// 允许访问上传的图片
app.use('/images', express.static('images'));

app.get('/',(req,res) => {
    res.send('good')
})

// 处理单文件上传
app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file || req.body.key !== 'luckean') {
    return res.status(400).json({
        message: 'Error!',
        code: 400
    });
  }

  // 获取文件相对路径并返回完整 URL
  const filePath = req.file.path.replace(__dirname, '').replace(/\\/g, '/'); // 适配 Windows 路径
  const imageUrl = `${req.protocol}://${req.get('host')}${filePath}`;

  res.json({
    message: '上传成功',
    data: imageUrl,
    code: 200
  });
});


app.listen(17070, () => {
  console.log('Server running on http://localhost:17070');
});

package

{
  "name": "ls",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "express": "^4.21.2",
    "multer": "^1.4.5-lts.1"
  }
}

Lucking