example.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. const BaseController = require('../base');
  3. const os = require('os');
  4. const fs = require('fs');
  5. const path = require('path');
  6. class ExampleController extends BaseController {
  7. async openLocalDir() {
  8. const self = this;
  9. const { ctx, service } = this;
  10. const body = ctx.request.body;
  11. const id = body.id;
  12. const data = {};
  13. let dir = '';
  14. switch (id) {
  15. case 'download' :
  16. dir = os.userInfo().homedir + '/Downloads';
  17. break;
  18. case 'picture' :
  19. dir = os.userInfo().homedir + '/Pictures';
  20. break;
  21. case 'doc' :
  22. dir = os.userInfo().homedir + '/Documents';
  23. break;
  24. case 'music' :
  25. dir = os.userInfo().homedir + '/Music';
  26. break;
  27. }
  28. await service.example.openLocalDir(dir);
  29. self.sendSuccess(data);
  30. }
  31. async uploadFile() {
  32. const self = this;
  33. const { ctx, service } = this;
  34. let tmpDir = service.storage.getStorageDir();
  35. // for (const file of ctx.request.files) {
  36. // this.app.logger.info('file:', file);
  37. // try {
  38. // let tmpFile = fs.readFileSync(file.filepath)
  39. // fs.writeFileSync(path.join(tmpDir, file.filename), tmpFile)
  40. // } finally {
  41. // await fs.unlink(file.filepath, function(){});
  42. // }
  43. // const fileStream = fs.createReadStream(path.join(tmpDir, file.filename))
  44. // const uploadRes = await service.example.uploadFileToSMMS(fileStream);
  45. // }
  46. const file = ctx.request.files[0];
  47. this.app.logger.info('file:', file);
  48. try {
  49. let tmpFile = fs.readFileSync(file.filepath)
  50. fs.writeFileSync(path.join(tmpDir, file.filename), tmpFile)
  51. } finally {
  52. await fs.unlink(file.filepath, function(){});
  53. }
  54. const fileStream = fs.createReadStream(path.join(tmpDir, file.filename))
  55. const uploadRes = await service.example.uploadFileToSMMS(fileStream);
  56. self.sendData(uploadRes);
  57. }
  58. }
  59. module.exports = ExampleController;