Created
November 13, 2012 14:58
-
-
Save anonymous/4066155 to your computer and use it in GitHub Desktop.
Valums file uploader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Image uploads | |
app.post('/upload', function (req, res) { | |
uploadFile(req, Common.conf.uploadpath, function (data) { | |
if (data.success) | |
res.send(JSON.stringify(data), {'Content-Type': 'text/plain'}, 200); | |
else | |
res.send(JSON.stringify(data), {'Content-Type': 'text/plain'}, 404); | |
}); | |
}); | |
// Mainfunction to recieve and process the file upload data asynchronously | |
uploadFile = function(req, targetdir, callback) { | |
// Moves the uploaded file from temp directory to it's destination | |
// and calls the callback with the JSON-data that could be returned. | |
var moveToDestination = function(sourcefile, targetfile) { | |
// Save big file | |
Common.gm(sourcefile) | |
.resize(800,800) | |
.quality(90) | |
.autoOrient() | |
.write(targetdir + fname, function (err) { | |
if (!err) { | |
console.log(' Big image saved. '); | |
} else { | |
console.error(err); | |
} | |
}); | |
Common.gm(sourcefile) | |
.resize(260,260) | |
.quality(85) | |
.autoOrient() | |
.write(targetdir + 'thumbs/' + fname, function (err) { | |
if (!err) { | |
console.log(' Thumbnail saved. '); | |
callback({success: true, file: fname}); | |
} else { | |
console.error(err); | |
} | |
}); | |
}; | |
// Direct async xhr stream data upload, yeah baby. | |
if(req.xhr) { | |
var fname = randomString() + '_' + randomString() + '.' + req.header('x-file-name').split('.').pop(); | |
// Be sure you can write to '/tmp/' | |
var tmpfile = '/tmp/'+Common.uuid.v1(); | |
// Open a temporary writestream | |
var ws = Common.fs.createWriteStream(tmpfile); | |
ws.on('error', function(err) { | |
console.log("uploadFile() - req.xhr - could not open writestream."); | |
callback({success: false, error: "Sorry, could not open writestream."}); | |
}); | |
ws.on('close', function(err) { | |
moveToDestination(tmpfile, targetdir+fname); | |
}); | |
// Writing filedata into writestream | |
req.on('data', function(data) { | |
ws.write(data); | |
}); | |
req.on('end', function() { | |
ws.end(); | |
}); | |
} | |
// Old form-based upload | |
else { | |
moveToDestination(req.files.qqfile.path, targetdir+req.files.qqfile.name); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment