如果我把我的视频文件存储在mongodb中,我可以如何为我的应用程序生成url



我无法解决这个问题。有很多方法

我需要类似https://localhost..的url。。

我的mongo数据库我的视频是存储如何获得

您必须将该文件保存在服务器目录中,并获取目录路径,然后使用主机名和端口保存在mongodb中

好吧,我们实际上并没有在MongoDB数据库中保存视频。相反,我们将它们保存在一个文件夹中,并将视频的路径保存在数据库中。
我使用NodeJS和MongoDB来实现您想要的功能。

步骤1

首先创建一个节点项目,并在项目中安装这些依赖项/库。

npm install express dotenv mongoose express-fileupload

express-fileupload库将允许您接受表单数据中的文件。它在req对象中创建一个属性files:[]

步骤2

一旦安装了所有的基本库,就可以继续执行第二步了。我们将在index.js / app.js文件中编写代码。

import express from "express";
import dotenv from 'dotenv';
import upload from 'express-fileupload';
import mongoose from "mongoose";
dotenv.config();
var PORT = process.env.PORT,
DB_URL = process.env.DB_URL;
console.clear();
mongoose.connect(DB_URL, (err) => {
if(err) console.error(err);
console.log('x1b[33mDatabase Connected!x1b[0m');
});
const app = express();
app.use(express.json());
app.use(upload());
app.use(cors());
app.use(express.static('public'));
app.listen(PORT, () => {
console.log(`x1b[92mServer is now up and running on:x1b[0m`);
console.log(`x1b[46mhttp://localhost:${PORT}x1b[0m`);
});

.env

PORT=3000
DB_URL="mongodb+srv://<user>:<password>@:<server.uri>/<db.name>?retryWrites=true&w=majority"

步骤3

现在,首先在项目的顶级目录中创建一个文件夹public,并在其中创建一个子文件夹profiles
您的所有图像都将保存在此处。一旦执行了这些说明,您就可以最终在主文件中创建一条路线。

app.post('/saveVideo', async (req, res) => {
try {
let videoFile = req.files?.video;
if (!videoFile) return res.status(400).json({
status: "error",
message: "Please add profile picture to continue.",
data: null,
});
// add file extensions check to identify if the file is a video
// right now, It accepts all kinds of files
let fileName = `public/profiles/${Date.now()}-${videoFile.name.replace(/ /g, '-').toLowerCase()}`;
await profilePicture.mv(fileName);
videoFile = fileName.replace("public", "");
// you can save this videoFile path in the database
return res.json({
status: "success",
message: "Profile Picture Updated!",
data: profilePicture
});
} catch (err) {
return res.status(500).json({
status: "error",
message: "An unexpected error occured while proceeding your request.",
data: null,
trace: err.message
})
})

最新更新