Skip to content

Instantly share code, notes, and snippets.

@bgkittrell
Created January 17, 2012 14:52
Show Gist options
  • Save bgkittrell/1626918 to your computer and use it in GitHub Desktop.
Save bgkittrell/1626918 to your computer and use it in GitHub Desktop.
http = require 'http'
fs = require 'fs'
util = require 'util'
connect = require 'connect'
uuid = require 'node-uuid'
require 'coffee-script'
UploadController = require './controllers/upload'
app = {}
app.mediaDir = '/tmp/media'
app.uploadDir = '/tmp/uploads'
uploadController = new UploadController(app)
options =
uploadDir: app.uploadDir
server = connect connect.bodyParser(options), connect.router (capp) ->
capp.post '/', (req, res, next) ->
uploadController.upload(req, res)
capp.get '/:fileName', (req, res) ->
filePath = path.join(app.mediaDir, req.params.fileName)
stat = fs.statSync(filePath)
read = fs.createReadStream filePath
util.pump read, res
server.listen(8080)
class UploadController
constructor: (app) ->
@app = app
upload: (req, res) ->
console.log req.files
file = req.files['image1']
fs.rename path.join(file.path), path.join(app.mediaDir, file.name)
ids = []
for name, image of req.files
do (name, image) ->
id = uuid.v4()
ids.push id
fullpath = path.join(directory(), id)
fs.rename file.path, path.join(fullpath, filename(file.name))
res.end JSON.stringify(ids)
directory: (id) ->
first = id.substring(0,2)
second = id.substring(2,4)
dir = path.join(app.mediaDir, first, second)
fs.mkdir dir
return dir
filename: (name) ->
name.replace(/\ /, '-').replace(/[^A-Za-z0-9\.\-_]/, '')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment