当前位置: 首页 > news >正文

Express + MongoDB 实现视频点播

一、安装依赖

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 });
  }
});

相关文章:

  • Linux文档编辑相关命令详解
  • 初识神经网络的分类问题
  • GAN、Diffusion与美颜SDK:AI如何驱动人脸美型API进化?
  • OpenGL ES -> GLSurfaceView纹理贴图
  • 坐标变换介绍与机器人九点标定的原理
  • 【JavaEE进阶】图书管理系统 - 柒
  • PAT 甲级 1107 并查集
  • 国产编辑器EverEdit - 超多样式设置
  • go 分布式redis锁的实现方式
  • AI是否能真正理解人类情感?从语音助手到情感机器人
  • C 语 言 --- 经 典 习 题 2
  • 第一次执行GameObject.Instantiate时可能出现明显的卡顿 如何解决该问题?
  • TCP/IP四层模型:从入门到精通
  • NVIDIA(英伟达) GPU 芯片架构发展史
  • <Rust><iced>基于rust使用iced构建GUI实例:图片浏览器
  • Spark核心之02:RDD、算子分类、常用算子
  • 设计模式:记录所有设计模式方便后续复习
  • 小白向:如何使用dify官方市场“ECharts图表生成”工具插件——dify入门案例
  • Sat- nerf深度损失
  • RPA 职业前景:个人职场发展的 “新机遇”
  • 李在明正式登记参选下届韩国总统
  • 拿出压箱底作品,北京交响乐团让上海观众享受音乐盛宴
  • 比特币价格重返10万美元,哪些因素使然?
  • AI药企英矽智能第三次递表港交所:去年亏损超1700万美元,收入多数来自对外授权
  • 本科生已发14篇SCI论文被指由其教授父亲挂名,重庆大学成立工作组核实
  • 上海将发布新一版不予行政处罚清单、首份减轻行政处罚清单