输出文件或图片

项目中有时候要输出图片等类型的数据,可以通过下面的方式进行:

控制器内输出图片:

  1. const file = this.app.root_path + '/static/upload/test.png';
  2. const filename = path.relative(path.dirname(file), file);
  3. this.ctx.set('Content-disposition', 'attachment; filename=' + filename);
  4. return this.write(fs.createReadStream(file));

或者中间件中这样写:

  1. ctx.set('Content-disposition', 'attachment; filename=' + filename);
  2. ctx.body = fs.createReadStream(file);