main.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var http = require('http'),
  2. qs = require('querystring'),
  3. fs = require('fs'),
  4. MAX_FILE_SIZE = 5 * 1024 * 1024,
  5. port = process.env.PORT || 8080,
  6. server;
  7. function respond(response, code, data, headers, encoding) {
  8. response.writeHead(code, headers);
  9. response.end(data, encoding);
  10. }
  11. server = http.createServer(function (request, response) {
  12. var rawBody = '';
  13. if (request.method === 'POST') {
  14. request.on('data', function (data) {
  15. if (rawBody.length <= MAX_FILE_SIZE) {
  16. rawBody += data;
  17. } else {
  18. respond(response, 413, 'Request entity too large.');
  19. }
  20. });
  21. request.on('end', function () {
  22. var body, content, charset;
  23. try {
  24. body = qs.parse(rawBody);
  25. } catch (e) {
  26. console.error('Parsing request data failed.', e);
  27. }
  28. if ( !body || !body.content || !body.filename || !/^[-\w]+\/[-\w\+\.]+$/.test(body.mime) || !/^[-\.\w]+[\.]?[-\w]+$/.test(body.filename) ) {
  29. respond(response, 400, 'Bad request.');
  30. return;
  31. }
  32. content = new Buffer(body.content, 'base64');
  33. charset = body.charset || 'UTF-8';
  34. respond(response, 200, content.toString('utf8'), {
  35. 'Content-Type': body.mime || 'application/octet-stream',
  36. 'Content-Disposition': 'attachment; filename="' + body.filename + '"',
  37. 'Content-Transfer-Encoding': 'binary',
  38. 'Cache-Control': 'public',
  39. 'Expires': 0
  40. }, charset);
  41. });
  42. }
  43. else if(request.method === 'GET') {
  44. respond(response, 200, 'server running...');
  45. }
  46. else {
  47. respond(response, 400, "Bad request.");
  48. }
  49. }).listen(port, function(){
  50. console.log('Listening on port %d', server.address().port);
  51. });