웹
nodejs, reactjs) mp4 파일 화면에 플레이 하기 - 개발 기록 3
전문 컨설턴트
2024. 5. 31. 11:39
nodejs)
play.router.js
const express = require('express');
const router = express.router();
const playcontroller = require('../controller/play.controller');
router.get('/video/:filename', playcontroller.playvideo);
module.exports = router;
play.controller.js
const path = require('path');
const fs = require('fs');
async function playVideo(req, res) {
const filename = req.params.filename;
const videoPath = path.join(__dirname, '..', 'uploads', filename);
const stat = fs.statSync(videoPath);
const fileSize = stat.size;
const range = req.headers.range;
if (range) {
const parts = range.replace(/bytes=/, "").split("-");
const start = parseInt(parts[0], 10);
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
const chunksize = (end - start) + 1;
const file = fs.createReadStream(videoPath, { start, end });
const head = {
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Accept-Ranges': 'bytes',
'Content-Length': chunksize,
'Content-Type': 'video/mp4',
};
res.writeHead(206, head);
file.pipe(res);
} else {
const head = {
'Content-Length': fileSize,
'Content-Type': 'video/mp4',
};
res.writeHead(200, head);
fs.createReadStream(videoPath).pipe(res);
}
}
module.exports = {
playVideo,
};
reactjs)
VideoPlayer.js
import React from 'react';
import { API_BASE_URL } from '../../config';
const VideoPlayer = ( { fileName } ) => {
return (
<div>
<video width="750" height="500" controls>
<source src={`${API_BASE_URL}/play/video/${fileName}`} type="video/mp4" />
Your browser does not support the video tag.
</video>
</div>
);
};
export default VideoPlayer;