Permalink
Browse files

Automatically generate filename for uploaded file

  • Loading branch information...
1 parent 060715e commit 438e44b74ce10088675201be092ac29417bb84b9 @vslinko committed Feb 12, 2013
Showing with 29 additions and 19 deletions.
  1. +28 −18 lib/rithis-stack/plugins/files.coffee
  2. +1 −1 package.json
@@ -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"
@@ -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()
View
@@ -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": {

0 comments on commit 438e44b

Please sign in to comment.