file-upload.js 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. const formidable = require('formidable');
  2. const fs = require('fs');
  3. const path = require('path');
  4. const Entities = require('html-entities').XmlEntities;
  5. const entities = new Entities();
  6. const filePath = path.resolve(__dirname, '..' + path.sep + 'upload');
  7. module.exports = function(request, response){
  8. const form = new formidable.IncomingForm();
  9. return new Promise((resolve, reject) => {
  10. form.parse(request, (err, fields, files) => {
  11. const file = files.file;
  12. const oldpath = file.path;
  13. const filename = file.name;
  14. const size = file.size;
  15. const id = Date.now().toString(36) + Math.random().toString(36).substr(3);
  16. const newpath = filePath + path.sep + entities.decode(filename);
  17. fs.rename(oldpath, newpath, err => {
  18. if (err) {
  19. reject(err);
  20. }else {
  21. resolve({
  22. id: id,
  23. name: filename,
  24. path: newpath,
  25. size: size
  26. })
  27. }
  28. })
  29. })
  30. });
  31. }