I am not able to solve this problem. there are many ways
I need url like https//local host..
My mongo db my video is store how i can get
I am not able to solve this problem. there are many ways
I need url like https//local host..
My mongo db my video is store how i can get
you have to save that file in server directory and get the directory path and save in mongodb with your host name and port
Well, We don't actually save videos in MongoDB database. Instead we save them in a folder and save the path to the video in the database.
I'm using NodeJS with MongoDB to achieve the functionality that you want.
First create a node project and install these dependencies/libraries in the project.
npm install express dotenv mongoose express-fileupload
express-fileupload
library will allow you to accept files in form-data. It creates a property files:[]
in the req
object.
Once, all the essential libraries are installed you can move forward with the second step. We'll write code in the index.js / app.js
file.
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"
Now first of all create a folder public
in the top level directory of your project and create a sub folder profiles
in it.
All of your images will be saved here. Once, You've performed these instructions you can finally create a route in your main file.
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
})
})