12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- 'use strict';
- const Controller = require('egg').Controller;
- const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
- const fs = require('fs');
- const assert = require('assert');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const _ = require('lodash');
- class HomeController extends Controller {
- constructor(ctx) {
- super(ctx);
- this.service = this.ctx.service.home;
- this.http = this.ctx.service.util.httpUtil;
- }
- async index() {
- const { ctx } = this;
- ctx.body = 'hi, egg';
- }
- async request() {
- const res = await this.service.request();
- this.ctx.body = res;
- }
- async upload() {
- const { appid } = this.ctx.params;
- assert(appid);
- const file = this.ctx.request.files[0];
- const uarr = this.ctx.request.url.split('/');
- uarr.pop();
- console.log(uarr);
- const uri = `${uarr.join('/')}/`;
- if (!file) throw new BusinessError(ErrorCode.FILE_FAULT, '未获取到文件');
- const { filepath } = file;
- const { filename } = file;
- const arr = filename.split('.');
- const name = new Date().getTime();
- const extension = `${_.last(arr)}`;
- const object = { uri, name, extension };
- const picBuffer = fs.readFileSync(filepath);
- const code = this.turnImageToBase64({ extension, buffer: picBuffer });
- if (code) object.code = code;
- // console.log(object);
- const reqUrl = '/files/server/upload';
- const res = await this.http.$post(reqUrl, object);
- console.log(res);
- const resData = _.get(res, 'data');
- if (resData) this.ctx.body = { errcode: 0, errmsg: 'ok', ...resData };
- else this.ctx.body = { errcode: -1, errmsg: '上传失败' };
- }
- /**
- * 转换图片为base64
- * @param {Object} object excel获取的图片object
- * @property extension 后缀,文件类型
- * @property buffer 图片内容,不含头部信息的,
- */
- turnImageToBase64(object = {}) {
- const { extension, buffer } = object;
- if (extension && buffer) {
- const suffix = object.extension;
- const ib = object.buffer.toString('base64');
- const base64 = `data:image/${suffix};base64,${ib}`;
- return base64;
- }
- }
- }
- module.exports = CrudController(HomeController, {});
|