upload.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. var path = require('path');
  2. var formidable = require('formidable');
  3. var fs = require('fs-extra');
  4. const uuidV1 = require('uuid/v1');
  5. exports.uploadImage = function(req, res){
  6. // create an incoming form object
  7. var form = new formidable.IncomingForm();
  8. // specify that we want to allow the user to upload multiple files in a single request
  9. form.multiples = false;
  10. // every time a file has been uploaded successfully,
  11. // rename it to it's original name
  12. form.on('file', function(field, file) {
  13. fileEndName = uuidV1() + file.name;
  14. //--------------------------------------------------------------------------
  15. // COWNOTE(n2omatt): fs.rename fails on cross device files.
  16. // So if the the tmpfs is mounted on /tmp (which is to be the default)
  17. // and the /tmp itself is on other device the call for fs.rename will
  18. // trigger an [Error: EXDEV: cross-device link not permitted...]
  19. //
  20. // This make sure that we always have the correct behaviour no matter
  21. // the actual underlying devices that we're on.
  22. //
  23. // The call of fs.remove is kind of optional, because by default
  24. // the contents of tmpfs is cleared upon reinitialization. But to
  25. // ensure that the disk space is preserved we're calling it here.
  26. //
  27. // Please beware of this and remove the fs.remove call if any performance
  28. // degradation is perceived at all.
  29. //
  30. // Other thing to keep in mind is that those functions aren't default
  31. // fs module calls, but instead fs-extra calls.
  32. //
  33. // Reference:
  34. // https://github.com/jprichardson/node-fs-extra
  35. fs.copySync(file.path, path.join(uploadDir + fileEndName));
  36. fs.remove(file.path);
  37. });
  38. // log any errors that occur
  39. form.on('error', function(err) {
  40. console.log('An error has occured: \n' + err);
  41. });
  42. // once all the files have been uploaded, send a response to the client
  43. form.on('end', function() {
  44. res.end('/media/' + fileEndName);
  45. });
  46. // parse the incoming request containing the form data
  47. form.parse(req);
  48. };