Skip to content

Commit

Permalink
Automatically generate filename for uploaded file
Browse files Browse the repository at this point in the history
  • Loading branch information
vslinko committed Feb 12, 2013
1 parent 060715e commit 438e44b
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
46 changes: 28 additions & 18 deletions lib/rithis-stack/plugins/files.coffee
@@ -1,3 +1,7 @@
crypto = require "crypto"
path = require "path"


module.exports = (stack, callback) ->
stack.app.get "/files/:filename", (req, res) ->
gs = new stack.mongodb.GridStore stack.connection.db, req.params.filename, "r"
Expand All @@ -21,32 +25,38 @@ module.exports = (stack, callback) ->


stack.app.post "/files", (req, res) ->
unless req.files.file and req.body.filename
unless req.files.file
return res.send 400

metadata = {}
for key, value of req.body
unless key is "filename" or key is "content-type"
crypto.randomBytes 64, (err, buffer) ->
if err
return res.send 500

filename = buffer.toString("hex") + path.extname(req.files.file.name)

metadata = {}
for key, value of req.body
metadata[key] = value

gs = new stack.mongodb.GridStore stack.connection.db, req.body.filename, "w",
content_type: req.body["content-type"] or "binary/octet-stream"
metadata: metadata
gs = new stack.mongodb.GridStore stack.connection.db, filename, "w",
content_type: req.files.file.type
metadata: metadata

gs.open (err) ->
if err
return res.send 500
gs.open (err) ->
if err
return res.send 500

if gs.length > 0
return gs.close ->
res.send 409
if gs.length > 0
return gs.close ->
res.send 409

gs.writeFile req.files.file.path, (err) ->
gs.close ->
if err
return res.send 500
gs.writeFile req.files.file.path, (err) ->
gs.close ->
if err
return res.send 500

res.send 201
res.set "Location", "/files/#{filename}"
res.send 201


callback()
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "rithis-stack",
"version": "0.1.1",
"version": "0.1.2",
"description": "Our web stack: express, mongoose, rithis-crud",
"keywords": ["web", "stack", "express", "mongoose", "crud"],
"author": {
Expand Down

0 comments on commit 438e44b

Please sign in to comment.