Last active
December 25, 2015 14:29
-
-
Save dpogorzelski/6990974 to your computer and use it in GitHub Desktop.
Client-side File Encryption: Backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.post('/file', function(req, res) { | |
//We create a write stream which will save the file to gridfs. | |
//"gridfs-stream" is great at this. | |
var writestream = gfs.createWriteStream({ | |
filename: req.files.file.name | |
}); | |
//fs.createReadStream() will read the file uploaded to tmp directory and | |
//pipe it to the write stream. | |
fs.createReadStream(req.files.file.path).pipe( | |
writestream.on('close', function(file) { | |
//The temporary file is deleted from local filesystem | |
fs.unlink(req.files.file.path); | |
//and the id sent back to angular so we can build a link to the file | |
res.send(file._id.toString()) | |
})); | |
}); | |
app.get('/file/:id', function(req, res) { | |
//We set up a read stream with the file id | |
var readstream = gfs.createReadStream({ | |
_id: req.params.id | |
}); | |
//Not really needed | |
res.set({ | |
'Content-Type': 'application/octet-stream' | |
}); | |
//This is a helper method which will set "Content-disposition: attachment" | |
//so the browser will download the file instead of trying to open it. | |
res.attachment(); | |
//Finally we pipe the stream | |
readstream.pipe(res); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment