FFmpeg란?
FFmpeg은 디지털 음성 스트림과 영상 스트림에 대해서 다양한 종류의 형태로 기록하고 변환하는 컴퓨터 프로그램이다. FFmpeg은 명령어를 직접 입력하는 방식으로 동작하며 여러가지 자유 소프트웨어와 오픈 소스 라이브러리로 구성되어 있다.
설치
npm
npm install fluent-ffmpeg
클라이언트 소스코드
const onDrop = (files) => {
let formData = new FormData();
const config = {
header: { 'content-type': 'multipart/form-data' }
}
formData.append("file", files[0])
//db저장부분이 파일의 path와 filename받아오기위한 api
axios.post('/api/video/uploadfiles', formData, config) //파일 전송시 header설정
.then(response => {
if (response.data.success) {
let variable = {
filePath: response.data.filePath, //백엔드에서 받아온 파일의 경로
fileName: response.data.fileName //백엔드에서 받아온 파일의 이름
}
setFilePath(response.data.filePath)
//썸네일만들기
axios.post('/api/video/thumbnail', variable)
.then(response => {
if (response.data.success) {
setDuration(response.data.fileDuration)//영상시간
setThumbnail(response.data.thumbsFilePath)//썸네일
}
})
}
})
}
서버측 소스코드
const multer = require('multer'); //비디오 업로드시
const ffmpeg = require('fluent-ffmpeg'); //썸네일 이미지 생성
const storage = multer.diskStorage({
destination: (req, file, cb) => { //저장소
cb(null, 'uploads')
},
filename: (req, file, cb) => { //파일이름
cb(null, `${Date.now()}_${file.originalname}`)
},
fileFilter: (req, file, cb) => { //파일형식 거르기
const ext = path.extname(file.originalname)
if (ext !== '.mp4') {
return cb(res.status(400).end('only jpg, png, mp4 is allowed'), false); //에러,성공여부false
}
cb(null, true) //error 값 x , 성공여부true
}
})
const upload = multer({ storage: storage }).single("file")
//db저장부분이 아닌 client에게 파일의 path와 filename을 알려주기위한 api (uploads폴더안에는 저장됨)
router.post("/uploadfiles", (req, res) => {
upload(req, res, err => {
if (err) {
return res.json({ success: false, err })
}
return res.json({ success: true, filePath: res.req.file.path, fileName: res.req.file.filename })
})
});
//썸네일 제작 ffmpeg 라이브러리이용->복붙
router.post("/thumbnail", (req, res) => {
let thumbsFilePath ="";
let fileDuration ="";
ffmpeg.ffprobe(req.body.filePath, function(err, metadata){
console.dir(metadata);
console.log(metadata.format.duration);
fileDuration = metadata.format.duration;
})
ffmpeg(req.body.filePath)
.on('filenames', function (filenames) {
console.log('Will generate ' + filenames.join(', '))
thumbsFilePath = "uploads/thumbnails/" + filenames[0];
})
.on('end', function () {
return res.json({ success: true, thumbsFilePath: thumbsFilePath, fileDuration: fileDuration})
})
.screenshots({
count: 3,
folder: 'uploads/thumbnails',
size:'320x240',
filename:'thumbnail-%b.png'
});
});
module.exports = router;
'Node.js' 카테고리의 다른 글
bcrypt (0) | 2022.01.16 |
---|---|
JSON Web Token(JWT) (0) | 2022.01.16 |
Multer (0) | 2022.01.16 |