2016-12-08 1 views
0

평균 스택을 사용하여 REST API를 작성하려고하는데 문제가 발생했습니다. 서버에 POST 요청으로 보낸 .txt 파일을 저장하고/uploads 폴더에 multer를 사용하여 저장합니다. 그런 다음 req.file 정보를 mongodb (경로 포함)의 모음에 저장합니다.GET 요청 후 파일 보내기 Node.js

제가 지금 가지고있는 문제점은 ObjectId를 사용하여 특정 파일에 대한 GET 요청을 처리 할 수 ​​있기를 원합니다. 그러나 파일 경로에서 파일을 가져 와서 GET 요청을하는 사용자에게 보내고 싶습니다.

지금은 전달 된 ObjectId에 해당하는 정보 만 반환합니다. 파일이 아닙니다. 어떻게 전체 .txt 파일을 다시 사용자에게 보낼 수 있습니까?

exports.findById = function(req, res) { 
try 
{ 
    var id = new require('mongodb').ObjectID(req.params.id); 
    console.log('Retrieving log: ' + id); 

    db.collection('logs', function(err, collection) { 
     if(err) 
     { 
      console.log(err); 
     } 
     else 
     { 
      collection.findOne({'_id':id}, function(err, item) { 
       if (err) { 
        console.log('Error finding log: ' + err); 
        res.send({'error':'An error has occurred'}); 
       } else { 
        console.log('' + item + ' found log'); 
        console.log(item.path); 
        var file = __dirname + item.path; 
        res.download(file); 
        //res.send(item); 
       } 
      }); 
     } 
    }); 
} 
catch (e) 
{ 
    console.log('Id passed not correct'); 
    res.send({'error':'Id passed not correct'}); 
} 

}};

답변

0

마지막으로 서버가 GET 요청에 응답했습니다.

데이터베이스에 저장된 파일의 경로를 찾아야했습니다.

collection.findOne({'_id':id}, function(err, item) { 
       if (err) 
       { 
        console.log('Error finding log: ' + err); 
        res.send({'error':'An error has occurred'}); 
       } 
       if (item) 
       { 
        //Create the path of the file wanted 
        filepath = path.join(__dirname, "../uploads", path.normalize(item.filename)); 
        //Send file with the joined file path 
        res.sendFile(filepath); 
       } 
       else 
       { 
        console.log("Could not find entry"); 
        res.send({'error':'No match found'}); 
       } 
      }); 

이렇게하면 파일의 전체 경로를 가져 와서 파일을 다시 보낼 수 있습니다.