Egg: 浏览器发送一个multipart/form-data文件上传表单,如何通过node转发到其他后端服务?

Created on 10 Oct 2017  ·  9Comments  ·  Source: eggjs/egg

* test() {
  const fileStream = yield ctx.getFileStream();
  const url = `${this.ctx.protocol}://${ctx.host}/stream`;
  const result = yield this.ctx.curl(url, {
    // 必须指定 method,支持 POST,PUT
    method: 'POST',
    // 以 stream 模式提交
    stream: fileStream,
  });
  this.ctx.status = result.status;
  this.ctx.set(result.headers);
  this.ctx.body = result.data;

}

这样发送的是Stream数据流,因为接口只接收multipart/form-data数据格式,如何egg获取到multipart/form-data 数据保留或者转化为multipart/form-data 格式发送到对应的url接口地址?

not follow template

All 9 comments

我看到可以通过formstream插件可以格式化如下:

const FormStream = require('formstream');
    * test() {
      const form = new FormStream();
      const fileStream = yield ctx.getFileStream();
      form.field('foo', 'bar');
      form.stream('file', fileStream, 'upload-logo.png');
      const url = `${this.ctx.protocol}://${ctx.host}/stream`;
      const result = yield this.ctx.curl(url, {
        // 必须指定 method,支持 POST,PUT
        method: 'POST',
        headers: form.headers(),
        // 以 stream 模式提交
        stream: form,
      });
      this.ctx.status = result.status;
      this.ctx.set(result.headers);
      this.ctx.body = result.data;
    }

有没有可以直接转发过去的方式?

就看对方接口支不支持

@popomore 这个是的,就是有没有直接可以转发数据的形式,不需要中转格式?

@a526672351 用代理的形式,直接将请求的 stream pipe 给下游,不要关心 multipart 的格式,伪代码:

const req = ctx.request.req;
await ctx.curl(url, { stream: req });

@dead-horse 我刚测试了你说的方法,转发过去的内容直接是空的,无法实现

我说了这个是伪代码.. 去了解一下 node http request 如何做 pipe 就好了。

@dead-horse 大佬,轻点怒,有没有文档分享学习下,谢谢。

大神问题解决了吗!@a526672351

按照您的伪代码方式实现之后java 端无法识别 multipart file , 求教 @dead-horse

Was this page helpful?
0 / 5 - 0 ratings

Related issues

popomore picture popomore  ·  70Comments

occultskyrong picture occultskyrong  ·  35Comments

popomore picture popomore  ·  53Comments

killagu picture killagu  ·  48Comments

popomore picture popomore  ·  59Comments