Express + MongoDB 实现文件上传

使用 `multer` 中间件来处理文件上传,同时将文件的元数据存储到 MongoDB 中。

一、安装依赖

bash 复制代码
npm install multer

二、核心代码

javascript 复制代码
// 定义文件模型

const fileSchema = new mongoose.Schema({

  originalname: String,

  mimetype: String,

  size: Number,

  path: String,

});

const File = mongoose.model("File", fileSchema);

// 配置 multer

const storage = multer.diskStorage({

  destination: function (req, file, cb) {

    cb(null, "uploads/");

  },

  filename: function (req, file, cb) {

    cb(null, Date.now() + path.extname(file.originalname));

  },

});

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

// 创建上传目录

const fs = require("fs");

if (!fs.existsSync("uploads")) {

  fs.mkdirSync("uploads");

}

// 处理文件上传

app.post("/upload", upload.single("file"), async (req, res) => {

  try {

    const { originalname, mimetype, size, path } = req.file;

    const newFile = new File({

      originalname,

      mimetype,

      size,

      path,

    });

    await newFile.save();

    res.status(200).json({ message: "文件上传成功", file: newFile });

  } catch (error) {

    res.status(500).json({ message: "文件上传失败", error: error.message });

  }

});
相关推荐
devpotato41 分钟前
缓存与数据库更新顺序不一致问题
java·数据库·redis
天若有情67344 分钟前
Node+MySQL小型全栈笔记项目实战课程分享
数据库·笔记·mysql
wxwx_bscxy3221 小时前
基于springboot宠物领养系统的设计与实现
数据库·spring boot·后端·spring·宠物
九月要晚安2 小时前
达梦DW与AFC对比
数据库
实战派K8S&DB2 小时前
如何在内网配置 TiDB 数据库 Agent
数据库·人工智能·分布式·tidb
实战派K8S&DB2 小时前
《基于 Dify + FastAPI + PyTiDB 搭建大模型驱动的 TiDB 智能运维 Agent》
运维·数据库·分布式·云原生·tidb·fastapi
SelectDB2 小时前
Apache Doris 5.0 年度版本前瞻(一):构建统一的多模湖仓实时分析平台
大数据·数据库·数据分析
小白学大数据2 小时前
超简单:用 Python 让 Excel 飞起来:用 openpyxl 把重复报表整理交给脚本
开发语言·数据库·python·excel
西索斯coding3 小时前
doubao-seed-2.1-turbo 调用一直 401 怎么办?pro 版同样的 Key 却正常——5 分钟排查定位指南
java·服务器·数据库·ai
袋鼠云数栈3 小时前
整库迁移与分库分表同步:批量数据搬迁的配置简化思路
jvm·数据库·oracle