file-upload.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536
  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. //获取文件的后缀名
  17. const extname = path.extname(filename);
  18. const shortPath = id + (extname || '');
  19. const fullPath = filePath + path.sep + shortPath;
  20. fs.rename(oldpath, fullPath, err => {
  21. if (err) {
  22. reject(err);
  23. }else {
  24. resolve({
  25. id: id,
  26. name: filename,
  27. path: shortPath,
  28. size: size
  29. })
  30. }
  31. })
  32. })
  33. });
  34. }