灏天阁

Node/Koa2[40]: 用户设置-接口

· Yin灏

图片上传接口

# 安装
npm i formidable-upload-koa fs-extra --save

处理上传图片接口

src/routes/api/utils.js

const router = require("koa-router")();
const { loginCheck } = require("../../middlewares/loginChecks");
const { saveFile } = require("../../controller/utils");

router.prefix("/api/utils");

const koaForm = require("formidable-upload-koa");

// 上传图片
router.post("/upload", loginCheck, koaForm(), async (ctx, next) => {
  const file = ctx.req.files["file"];
  const { size, path, name, type } = file;
  // controller
  ctx.body = await saveFile({
    name,
    type,
    size,
    filePath: path,
  });
});

module.exports = router;

controller 层

src/controller/utils.js

const { ErrorModel, SuccessModel } = require("../model/ResModel");
const { uploadFileSizeFailInfo } = require("../model/ErrorInfo");
const fse = require("fs-extra");
const path = require("path");

// 要在根目录下新建 uploadFiles 文件夹,和 src 平级
const DIST_FOLDER_PATH = path.join(__dirname, "..", "..", "uploadFiles");
const MAX_SIZE = 1024 * 1024 * 1024; // 1M

// 是否需要创建目录
fse.pathExists(DIST_FOLDER_PATH).then((exist) => {
  if (!exist) {
    fse.ensureDir(DIST_FOLDER_PATH);
  }
});

async function saveFile({ name, type, size, filePath }) {
  if (size > MAX_SIZE) {
    // 删除文件
    await fse.remove(filePath);
    return new ErrorModel(uploadFileSizeFailInfo);
  }
  // 移动文件
  const fileName = Date.now() + "." + name; // 防止重名
  const distFilePath = path.join(DIST_FOLDER_PATH, fileName);
  await fse.move(filePath, distFilePath);
  // 返回信息
  return new SuccessModel({
    url: "/" + fileName,
  });
}

module.exports = {
  saveFile,
};

app.js 中配置图片的访问路径

src/app.js

// 注册新建接口路由
const utilsAPIRouter = require("./routes/api/utils");
//...
const path = require("path");
const koaStatic = require("koa-static");
//...
app.use(koaStatic(__dirname + "/public"));
app.use(koaStatic(path.join(__dirname, "..", "uploadFiles")));

//...
app.use(utilsAPIRouter.routes(), utilsAPIRouter.allowedMethods());

- Book Lists -