欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > Express + MongoDB 实现文件上传

Express + MongoDB 实现文件上传

2025/3/10 11:26:48 来源:https://blog.csdn.net/weixin_64684095/article/details/145939573  浏览:    关键词:Express + MongoDB 实现文件上传

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

一、安装依赖

npm install multer

二、核心代码

// 定义文件模型const fileSchema = new mongoose.Schema({originalname: String,mimetype: String,size: Number,path: String,});const File = mongoose.model("File", fileSchema);// 配置 multerconst 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 });}});

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词