upload.js 927 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. (function (req, res) {
  2. if (req.method === 'POST') {
  3. var busboy = new (require('busboy'))({ headers: req.headers })
  4. , uploads = [];
  5. busboy.on('file', function (fieldName, file, fileName, encoding, mimeType) {
  6. var splitFileName = fileName ? fileName.split('.') : null
  7. , extension = splitFileName ? "." + splitFileName[splitFileName.length - 1] : ""
  8. , newFileName = $.lib.shortid() + extension
  9. , uploadPath = require('path').resolve($.options.upload.location, newFileName)
  10. console.log("Uploading", fileName, "to", uploadPath);
  11. uploads.push(newFileName);
  12. file.pipe(require('fs').createWriteStream(uploadPath));
  13. });
  14. busboy.on('finish', function () {
  15. res.writeHead(200, { 'Connection': 'close'})
  16. res.end(JSON.stringify({uploaded: uploads}))
  17. })
  18. return req.pipe(busboy);
  19. } else {
  20. res.writeHead(404);
  21. res.end();
  22. }
  23. })