const bodyParser = require("body-parser");
const path = require("path");
const express = require("express");
const app =  express();
const fs = require("fs");

// 解析有效路径
function resolvePath (dir) {
    return path.join(__dirname, dir);
};

// 静态文件
app.use(express.static(resolvePath("/public")));

// 固定写法，处理 POST 请求
// https://expressjs.com/en/4x/api.html#req.body
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ extended: true }));

// 一个上传的接口
app.post("/upload", function (req, res) {
    const { fileName, fileData } = req.body;
    // base64 => buffer
    console.log(fileName)
    console.log(fileData)

    const chunk = Buffer.from(fileData, "base64");
    const imgUrl = resolvePath(`public/${fileName}`);
    // buffer 写入文件
    fs.writeFileSync(imgUrl, chunk);
    // 返回结果
    res.json({
        code: "0",
        message: "success",
        imgUrl: `http://localhost:48488/${fileName}`
    });
});

// 启动服务
const port = 48488;
app.listen(port, function () {
    console.log(`listen port ${port}`);
});