Skip to content

Instantly share code, notes, and snippets.

@coderaven
Forked from tkh44/FileController.js
Created January 28, 2014 21:31
Show Gist options
  • Save coderaven/8676952 to your computer and use it in GitHub Desktop.
Save coderaven/8676952 to your computer and use it in GitHub Desktop.

Setup

cd /your/project/dir

sails generate controller upload upload

sails generate file get

npm install shortid mkdirp -D
module.exports = {
get: function (req, res) {
res.sendfile(req.path.substr(1));
},
_config: {
rest: false,
shortcuts: false
}
};
module.exports.routes = {
'/': {
view: 'home/index'
},
'get /public/images/*': {
controller: 'FileController',
action: 'get'
}
};
<form id="uploadForm"
enctype="multipart/form-data"
action="/upload/upload"
method="post">
<input type="file" id="userPhotoInput" name="userPhoto" />
</form>
var sid = require('shortid');
var fs = require('fs');
var mkdirp = require('mkdirp');
//var io = require('socket.io');
var UPLOAD_PATH = 'public/images';
// Setup id generator
sid.characters('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$@');
sid.seed(42);
function safeFilename(name) {
name = name.replace(/ /g, '-');
name = name.replace(/[^A-Za-z0-9-_\.]/g, '');
name = name.replace(/\.+/g, '.');
name = name.replace(/-+/g, '-');
name = name.replace(/_+/g, '_');
return name;
}
function fileMinusExt(fileName) {
return fileName.split('.').slice(0, -1).join('.');
}
function fileExtension(fileName) {
return fileName.split('.').slice(-1);
}
// Where you would do your processing, etc
// Stubbed out for now
function processImage(id, name, path, cb) {
console.log('Processing image');
cb(null, {
'result': 'success',
'id': id,
'name': name,
'path': path
});
}
module.exports = {
upload: function (req, res) {
var file = req.files.userPhoto,
id = sid.generate(),
fileName = id + "." + fileExtension(safeFilename(file.name)),
dirPath = UPLOAD_PATH + '/' + id,
filePath = dirPath + '/' + fileName;
try {
mkdirp.sync(dirPath, 0755);
} catch (e) {
console.log(e);
}
fs.readFile(file.path, function (err, data) {
if (err) {
res.json({'error': 'could not read file'});
} else {
fs.writeFile(filePath, data, function (err) {
if (err) {
res.json({'error': 'could not write file to storage'});
} else {
processImage(id, fileName, filePath, function (err, data) {
if (err) {
res.json(err);
} else {
res.json(data);
}
});
}
})
}
});
},
/**
* Overrides for the settings in `config/controllers.js`
* (specific to GifController)
*/
_config: {}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment