nodejs用egg框架实现图片上传

1.创建app/public/admin/upload 文件夹用于存放上传的图片
2.在app/service/tools.js(工具)下写一个文件上传的方法
 /**
   * 获取文件上传目录
   * @param {*} filename
   */
  async getUploadFile(filename) {
    // 1、获取当前日期     20180920
    let day = sd.format(new Date(), 'YYYYMMDD');
    // 2、创建图片保存的路径
    let dir = path.join(this.config.uploadDir, day);
    await mkdirp(dir); // 不存在就创建目录
    let date = Date.now(); /* 毫秒数*/
    // 返回图片保存的路径
    let uploadDir = path.join(dir, date + path.extname(filename));
    // app\public\admin\upload\20190914\1536895331444.png
    return {
      uploadDir,
      saveDir: this.ctx.origin + uploadDir.slice(3).replace(/\\/g, '/'),
    };
  }

3.在app/controller/XXX.js 文件下面调用方法
   async saveAdvertising() {

    const parts = this.ctx.multipart({ autoFields: true });
    let files = {};
    let stream;
    while ((stream = await parts()) != null) {
      if (!stream.filename) {
        break;
      }
      const fieldname = stream.fieldname; // file表单的名字

      // 上传图片的目录
      const dir = await this.service.tools.getUploadFile(stream.filename);
      const target = dir.uploadDir;
      const writeStream = fs.createWriteStream(target);

      await pump(stream, writeStream);

      files = Object.assign(files, {
        [fieldname]: dir.saveDir,
      });
    }
    const params = Object.assign(files, parts.field);
     const params = Object.assign(files, parts.field);
    if (params.action == 0) { // 添加分享
      await this.service.advertising.addAdvertising(params);
    //   await this.service.operationLog.saveOperationLog(OPERATION_TYPE_CREATE, result, SYSTEM, SHARE);
    } else if (params.action == 1) { // 修改分享
    //   delete params.action;
      //   await this.service.operationLog.saveOperationLog(OPERATION_TYPE_UPDATE, params, SYSTEM, SHARE);
      await this.service.advertising.editAdvertising(params);
    }
    this.ctx.body = {
      status: 0,
    };
  }

你可能感兴趣的:(nodejs用egg框架实现图片上传)