2016-12-30 4 views
0

NodeJS를 사용하여 비디오 BLOB 객체를 Mongo DB에 업로드해야합니다. 비디오의 경우 video.js를 사용하고 있습니다. https://github.com/collab-project/videojs-record 아래와 같이 Ajax 호출을 사용하여 NodeJS에 blob 객체를 보내고 있습니다. 여기nodejs에서 Mongo DB로 video/webm 유형의 blob 객체를 업로드하는 방법은 무엇입니까?

var file={ 
    name:'abc', 
    data: player.recordedData.video 
}; 
$.ajax({ 
     type: 'POST', 
     url: '/uploadVideo', 
     data: file, 
     dataType: 'JSON' 

}).done(function(data) { 
       alert("success"); 
}); 

파일 내가 코드

router.post('/uploadVideo',function (req, res ,next) { 
    var file=req.body; 
    console.log("file"+file); 
    var collection = db.get('test'); 
       collection.insert(file, function(err, result){ 
       console.log('video saved in mongo db'); 
        res.send(file); 
       }); 

}); 

콘솔 문 아래에있는 Node.js를 끝에서 등 파일 이름, BLOB 데이터와 같은 다른 필드를 포함하는 내 컬렉션에 저장하고 싶었 JSON 객체 인 파일 객체가 제대로 인쇄됩니다. mongo DB 컬렉션에 JSON을 삽입하는 중 500 오류가 발생합니다.

누구나 컬렉션에 BLOB를 삽입 할 수있는 솔루션을 제공 할 수 있습니까? 또한 내 코드에 버그가 있는지 알려주십시오. 감사합니다.

+0

우리에게 전체 오류를주고'CONSOLE.LOG 같은 것을 할 (대해서 typeof (파일))'바랍니다. – Kristian

+0

console.log (typeof (file))를 출력하면 console에 String이 출력됩니다. – Vrushali

+0

데이터베이스에 얼룩을 채우는 것이 일반적으로 좋지 않다는 것을 발견했습니다. 일반적으로 비용이 많이 들며 일반적으로 더 많은 작업이 필요합니다. 대신 올바른 작업에 적합한 도구를 사용합니다. 대량 저장 공간 (예 : S3, 데이터베이스 레코드 또는 문서)은 URL 참조를 가져옵니다. – Paul

답변

0

어떤 미들웨어를 사용하고 있는지 잘 모르겠습니다. 다음은 multerbody-parser을 사용하는 작업 샘플입니다. 코드의

중요한 부분은 : -

양식 데이터 필드 이름 (uploadfile)이 일치해야합니다. 그런 다음 다운로드 한 위치에서 fs을 사용하여 파일을 읽고 MongoDB 컬렉션에 삽입 할 문서에 파일을 설정합니다.

upload.single('uploadfile'); 


insertdata["file"] = fs.readFileSync(req.file.path); 

양식 데이터 필드 이름 : -

File upload: <input type="file" name="uploadfile"><br> 

전체 HTML 양식 : -

<form action="http://localhost:3000/filesave" enctype="multipart/form-data" method="post"> 
    Username: <input type="text" name="username"><br> 
    File upload: <input type="file" name="uploadfile"><br> 
    <input type="submit" value="Send"> 
</form> 

근무 코드 : -

var express = require('express'); 
var Db = require('mongodb').Db, 
    Server = require('mongodb').Server, 
    bodyParser = require('body-parser') 
    fs = require('fs'); 

var db = new Db('test', new Server('localhost', 27017)); 

var multer = require('multer'); 
var upload = multer({ dest: 'uploads/' }); 


var collection, dbObj; 
module.exports = { 

}; 

var app = express(); 

app.use(bodyParser.json()); // for parsing application/json 
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded 

var exports = module.exports; 

app.post("/filesave", upload.single('uploadfile'), function (req, res) { 
    db.open(function (err, success) { 
     if (err) { 
      console.log("DB connection error"); 
     } else { 
      console.log("DB connection is successful"); 
      console.log(req.body.username); 
      console.log(req.file); 
      var insertdata ={}; 
      insertdata["username"] = req.body.username; 
      insertdata["file"] = fs.readFileSync(req.file.path); 

      db.collection("filesave").insert(insertdata, function (inserr, result) { 
       if (inserr) { 
        console.log(inserr); 
        db.close(true); 
        res.json(inserr); 
       } else { 
        db.close(true); 
        res.json("Successfully persisted in database"); 
       } 
      }); 
     } 
    }) 


}); 

app.listen(3000); 
MongoDB를 수집 저장개

데이터 : -

Binary data saved in Mongo Collection

+0

오디오 및 비디오 파일 업로드에 동일한 코드를 사용할 수 있습니까? – Vrushali

+0

예, 데이터는 바이너리로 저장됩니다. 그러나 MongoDB 컬렉션의 최대 크기는 문서의 경우 4MB이며, 데이터가 4MB를 초과하는 경우 MongoDB의 GridFS 기능을 사용해야 할 수도 있습니다. 또한 파일을 렌더링하는 동안 파일의 올바른 내용 유형을 사용해야 할 수도 있습니다. – notionquest

관련 문제