home.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
  4. const fs = require('fs');
  5. const assert = require('assert');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. const _ = require('lodash');
  8. class HomeController extends Controller {
  9. constructor(ctx) {
  10. super(ctx);
  11. this.service = this.ctx.service.home;
  12. this.http = this.ctx.service.util.httpUtil;
  13. }
  14. async index() {
  15. const { ctx } = this;
  16. ctx.body = 'hi, egg';
  17. }
  18. async request() {
  19. const res = await this.service.request();
  20. this.ctx.body = res;
  21. }
  22. async upload() {
  23. const { appid } = this.ctx.params;
  24. assert(appid);
  25. const file = this.ctx.request.files[0];
  26. const uarr = this.ctx.request.url.split('/');
  27. uarr.pop();
  28. console.log(uarr);
  29. const uri = `${uarr.join('/')}/`;
  30. if (!file) throw new BusinessError(ErrorCode.FILE_FAULT, '未获取到文件');
  31. const { filepath } = file;
  32. const { filename } = file;
  33. const arr = filename.split('.');
  34. const name = new Date().getTime();
  35. const extension = `${_.last(arr)}`;
  36. const object = { uri, name, extension };
  37. const picBuffer = fs.readFileSync(filepath);
  38. const code = this.turnImageToBase64({ extension, buffer: picBuffer });
  39. if (code) object.code = code;
  40. // console.log(object);
  41. const reqUrl = '/files/server/upload';
  42. const res = await this.http.$post(reqUrl, object);
  43. console.log(res);
  44. const resData = _.get(res, 'data');
  45. if (resData) this.ctx.body = { errcode: 0, errmsg: 'ok', ...resData };
  46. else this.ctx.body = { errcode: -1, errmsg: '上传失败' };
  47. }
  48. /**
  49. * 转换图片为base64
  50. * @param {Object} object excel获取的图片object
  51. * @property extension 后缀,文件类型
  52. * @property buffer 图片内容,不含头部信息的,
  53. */
  54. turnImageToBase64(object = {}) {
  55. const { extension, buffer } = object;
  56. if (extension && buffer) {
  57. const suffix = object.extension;
  58. const ib = object.buffer.toString('base64');
  59. const base64 = `data:image/${suffix};base64,${ib}`;
  60. return base64;
  61. }
  62. }
  63. }
  64. module.exports = CrudController(HomeController, {});