Express+MongoDB实现视频点播
- 软件开发
- 2025-09-15 00:12:01

一、安装依赖 npm install multer 二、编写代码 1. 定义视频模型 const mongoose = require("mongoose"); const videoSchema = new mongoose.Schema({ title: { type: String, required: true }, description: { type: String }, filePath: { type: String, required: true }, thumbnailPath: { type: String }, uploadDate: { type: Date, default: Date.now }, }); module.exports = mongoose.model("Video", videoSchema); 2. 配置 Express 服务器和 MongoDB 连接 // 配置 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 }); // 静态文件服务,用于访问视频文件 app.use("/public", express.static(path.join(__dirname, "public"))); // 处理视频上传 app.post("/upload", upload.single("video"), async (req, res) => { try { const { title, description } = req.body; const filePath = `/public/videos/${req.file.filename}`; const newVideo = new Video({ title, description, filePath, }); await newVideo.save(); res.status(200).json({ message: "视频上传成功", video: newVideo }); } catch (error) { res.status(500).json({ message: "视频上传失败", error: error.message }); } }); // 获取视频列表 app.get("/videos", async (req, res) => { try { const videos = await Video.find(); res.status(200).json(videos); } catch (error) { res.status(500).json({ message: "获取视频列表失败", error: error.message }); } }); // 播放视频 app.get("/videos/:id", async (req, res) => { try { const video = await Video.findById(req.params.id); if (!video) { return res.status(404).json({ message: "视频未找到" }); } res.sendFile(path.join(__dirname, video.filePath)); } catch (error) { res.status(500).json({ message: "播放视频失败", error: error.message }); } });
Express+MongoDB实现视频点播由讯客互联软件开发栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“Express+MongoDB实现视频点播”