0

i'm new to CouchDB and recently i create download portal using Express. I want to make sure that only authorize users will able to download so i create checking procedure in app.js (using express) like this :

app.get("/download/:id/:file", function (req, res) {
   var filename = req.params.file;
   var docI= req.params.id;
   if(userHasPrivileges()){
       db.getAttachment(publicationID, filename, function(err, reply){
           // WHAT SHOULD I DO HERE ?
       })
   }
}

the problem is i can't make cradle.io (https://github.com/cloudhead/cradle#creatingupdating-documents) to send the file directly to user. I don't want to use direct link from database, since it'll make unauthorized user be able to download file. The problem is: i don't really know how to send file that I just get from getAttachment() method to user's browser.

Thx for help

DennyHiu
  • 4,861
  • 8
  • 48
  • 80
  • What you should do in function(err, reply)? See answer here: http://stackoverflow.com/a/6618531/813080 – damphat Jan 01 '14 at 09:30
  • just to send file to client's browser without exposing its real file path (like http://localhost:5984/dbname/doc.pdf). Your solution above actually works! but i think it's incomplete, i just managed to download 1kB of the whole file so the file is broken. Stream needed ? – DennyHiu Jan 01 '14 at 09:48
  • Not really understand what you expect, you can send filename to broswer (not full path), then browser can save as to disk with that filename. – damphat Jan 01 '14 at 11:37
  • what i want to do is to make this couchdb URL: http://localhost:5984/dbname/filename.pdf turn into this via express: http://localhost:3000/publication/get/5fc7f959c818a4d503495a31770011d3/filename.pdf doing so will make me able to check wheter a user has privileges to download or not – DennyHiu Jan 01 '14 at 12:05

1 Answers1

3

In couchdb, db.getAttachment return a Stream, so you can pipe that stream to http response object:

getAttachment().pipe(httpResponseObject)  

Full code:

app.get("/download/:id/:file", function (req, res) {
   var filename = req.params.file;
   var docI= req.params.id;
   if(userHasPrivileges()){
       res.attachment(filename);
       db.getAttachment(publicationID, filename, function(err){ }).pipe(res);
   }
}

If your attachments are big data such as big images, mp3s or videos, you should support range download. Range in headers may allow browsers download/re-download the part they need.

Nodejs - HTTP Range support / Partial file download

Community
  • 1
  • 1
damphat
  • 18,246
  • 8
  • 45
  • 59