upload.js 965 B

12345678910111213141516171819202122232425262728293031323334353637
  1. var path = require('path');
  2. var formidable = require('formidable');
  3. var fs = require('fs');
  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 orignal name
  12. form.on('file', function(field, file) {
  13. fileEndName = uuidV1() + file.name;
  14. fs.rename(file.path, path.join(uploadDir + fileEndName));
  15. });
  16. // log any errors that occur
  17. form.on('error', function(err) {
  18. console.log('An error has occured: \n' + err);
  19. });
  20. // once all the files have been uploaded, send a response to the client
  21. form.on('end', function() {
  22. res.end('/media/' + fileEndName);
  23. });
  24. // parse the incoming request containing the form data
  25. form.parse(req);
  26. };