Skip to content

Instantly share code, notes, and snippets.

@digilord
Last active August 29, 2015 14:05
Show Gist options
  • Save digilord/0e1d1dcc9c9366f1be80 to your computer and use it in GitHub Desktop.
Save digilord/0e1d1dcc9c9366f1be80 to your computer and use it in GitHub Desktop.
@Media = new Meteor.Collection('media')
Media.allow
insert: (userId, doc) ->
return userId && (doc.user == userId)
update: (userId, doc, fields, modifier) ->
return userId == doc.user
remove: (userId, doc) ->
return userId && (doc.user == userId)
Media.deny
insert: (userId, doc) ->
doc.createdAt = "#{moment().unix()}"
return false;
update: (userId, docs, fields, modifier) ->
modifier.$set.updatedAt = "#{moment().unix()}"
return false
decodeBase64Media = (dataString) ->
matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)
response = {}
if matches.length isnt 3
return new Error('Invalid input string')
response.type = matches[1]
response.data = new Buffer(matches[2], 'base64')
return response
Meteor.methods
FileUpload: (values) ->
if Meteor.isServer
# NPM requirements
fs = Npm.require('fs')
path = Npm.require('path')
console.log('File Upload in progress')
# Pull out the Base64 data to be stored on disk.
base64_file = values.file.data
delete values.file.data
file = values.file
_filename = file.name
# Save the media WITHOUT the data as mongo has a 16MB limit on
# document sizes.
_id = Media.findOne({name: _filename})._id
# Need to get the path that this file is located in.
basepath = path.resolve('.')
# It just so happens that the apps root path is six steps up from the base path of THIS file.
app_root_path = basepath.replace('.meteor/local/build/programs/server','')
app_root_path = app_root_path.replace('/bundle/programs/public/server','')
media_dir = path.resolve("#{app_root_path}/../media/#{_id}")
if fs.existsSync(media_dir) isnt true
mkdirP.sync(media_dir)
_filePath = "#{media_dir}/#{_filename}"
console.log "Media Directory: ", media_dir
console.log "Application Base Path: ", app_root_path
file_data = decodeBase64Media(base64_file)
console.log "Writing: ", _filePath
fs.writeFileSync(_filePath, file_data.data)
Media.update({_id: _id}, {$set: {complete: true}})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment