Skip to content

Instantly share code, notes, and snippets.

@robksawyer
Created October 31, 2014 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robksawyer/f739b110f580e025420e to your computer and use it in GitHub Desktop.
Save robksawyer/f739b110f580e025420e to your computer and use it in GitHub Desktop.
SailsJS: Ajax Image Upload
//Source: https://github.com/balderdashy/sails/issues/27
var UUIDGenerator = require('node-uuid');
var DirectoryController = {
// uploads a file to a directory
upload: function(req, res) {
// Parse form data from server
var parsedFormData = JSON.parse(req.param('data'));
// Iterate through each uploaded file
var resultSet= [];
async.forEach(req.files.files,function(file,cb) {
async.auto({
// Calculate new path and filename, using a UUID and the old extension
metadata: function(cb){
var uuid = UUIDGenerator.v1(),
newFileName= uuid + "." + _.str.fileExtension(file.name),
newPath= config.appPath+"/public/files/"+newFileName;
cb(null,{
uuid: uuid,
newFileName: newFileName,
newPath: newPath
});
},
// Read temp file
readFile: function(cb,r){
console.log(file.path);
fs.readFile(file.path,cb);
},
// Save File to database
saveToDb: ['metadata',function(cb,r){
File.create({
name: file.name,
size: file.size,
fsName: r.metadata.newFileName
}).success(function(f) {
// Move file into target directory, inheriting permissions
f.mv(parsedFormData.parent.id,cb);
});
}],
// Write file to destination
writeFile: ['readFile','metadata',function(cb,r){
console.log("writing to",r.metadata.newPath);
console.log("file data",r.readFile,r.metadata);
fs.writeFile(r.metadata.newPath,r.readFile,cb);
}]
},function(err,res){
resultSet.push({
id: res.saveToDb.id,
name: res.saveToDb.name,
size: res.saveToDb.size,
DirectoryId: parsedFormData.parent.id
})
cb(err,res);
});
},
// And respond
function(err) {
// Respond to client with success or failure
if (err) { res.json({success:false, error: err}); }
else { res.json({ success: true}); }
});
},
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment