Skip to content

Commit

Permalink
Added support for file uploads
Browse files Browse the repository at this point in the history
  • Loading branch information
jhbertram committed May 12, 2012
1 parent 109fe18 commit eec15cb
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
61 changes: 61 additions & 0 deletions controllers/uploads.coffee
@@ -0,0 +1,61 @@
cradle = require 'cradle'
moment = require 'moment'
fs = require 'fs'
config = require('../config').config

class Upload
constructor: (host, port) ->
@connect = new cradle.Connection config.db.host, config.db.port, {
cache: true
raw: false
}
@db = @connect.database 'couchpress'

findAll: (callback) ->
@db.view 'couchpress/uploads_all', {descending: true}, (err, res) ->
if (err)
callback err
else
docs = []
res.forEach (row) ->
row.created_at = moment(row.created_at).fromNow()
docs.push row
callback null, docs

findById: (slug, filename, callback) ->
thatdb = @db
thatdb.get slug, (err, doc) ->
stream = thatdb.getAttachment slug, filename
data = []
dataLen = 0
stream.on 'data', (chunk) ->
data.push chunk
dataLen += chunk.length
stream.on 'end', ->
buf = new Buffer(dataLen)
pos = 0
for chunk in data
chunk.copy buf, pos
pos += chunk.length
doc.data = buf;
callback(null, doc)

save: (article, reqfile, callback) ->
thatdb = @db
article.type = 'upload'
article.created_at = new Date()
article.size = reqfile.size
fs.readFile reqfile.path, (err, data) ->
article._attachments = {}
article._attachments[article.filename] = {
content_type: reqfile.type
data: data.toString('base64')
}
thatdb.save article, (err, res) ->
if (err)
callback(err)
else
callback(null, res)


exports.uploads = new Upload()
18 changes: 18 additions & 0 deletions views/admin/uploads.jade
@@ -0,0 +1,18 @@
h2 New File
form(method='post', action='/admin/uploads', id='uploader', enctype='multipart/form-data')
input(type='text', placeholder='File Title', name='title')
input(type='file', placeholder='Upload a file', name='upload')
input(type='submit', value='Upload', id='go')
h2 Existing Files
- if(typeof(articles) != 'undefined')
- each article in articles
- var slug = '/upload/' + article._id + '/' + article.filename
.article
h1= article.filename
h2= article.title
span.type= article._attachments[article.filename].content_type
span.slug
a(href= slug, target='_blank')= slug
span.created= article.created_at + ' by ' + article.user
- else
.article='No uploads'

0 comments on commit eec15cb

Please sign in to comment.