node.js - 将 multipart/form-data 请求通过管道传输到另一个请求,同时更改 Node.js 中的某些字段名称

标签 node.js file express stream multipartform-data

我想将 multipart/form-data 中的文件上传请求流式传输到另一台服务器,并同时更改一些字段名称。

我不想将文件临时存储在磁盘上,也不想将文件完全存储在内存中。

我尝试使用 multer、busboy 和 multiparty。我认为通过使用自定义转换流我已经更接近了,但它还没有工作。

const express = require('express');
const request = require('request');
const { Transform } = require('stream');

const router = express.Router();

class TransformStream extends Transform {
  _transform(chunk, encoding, callback) {
    // here I tried to manipulate the chunk
    this.push(chunk);
    callback();
  }

  _flush(callback) {
    callback();
  }
}

router.post('/', function pipeFile(req, res) {
  const transformStream = new TransformStream();
  req.pipe(transformStream).pipe(request.post('http://somewhere.com'));
  res.sendStatus(204);
});

我尝试操作 _transform 中的 block ,但没有成功 (EPIPE)。听起来很老套,他们有更好的解决方案吗?

最佳答案

这是使用 replacestream 的解决方案以及content-disposition .

const replaceStream = require('replacestream');
const contentDisposition = require('content-disposition');

router.post('/', function pipeFile(req, res) {

  let changeFields = replaceStream(/Content-Disposition:\s+(.+)/g, (match, p1) => {
    // Parse header
    let {type, parameters} = contentDisposition.parse(p1);

    // Change the desired field
    parameters.name = "foo";

    // Prepare replacement
    let ret = `Content-Disposition: ${type}`;
    for(let key in parameters) {
      ret += `; ${key}="${parameters[key]}"`;
    }

    return ret;
  })

  req.pipe(changeFields)
  .pipe(request.post('http://somewhere.com'))
  .on('end', () => {
    res.sendStatus(204);
  });
});

关于node.js - 将 multipart/form-data 请求通过管道传输到另一个请求,同时更改 Node.js 中的某些字段名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58116079/

相关文章:

node.js - 将编译的 typescript 部署到 lambda 时导入模块错误

C++ 解析为自定义语言解释器

c++ - 当 0 是行中的最后一个整数时,如何使用 C++ 检测你已经到达 fgets 整数字符串的末尾?

express - 如何在 Express 中将所有请求作为过滤上下文处理?

node.js - cookie 和 cookieSession 的区别?

node.js - 构建 Node.js 和 Socket.io 应用程序的最佳实践?

node.js - 无法使用常用命令升级Node版本

javascript - 如何使用 riot-lol-api 连续发出多个请求?

javascript - 使用 Nodejs Post 请求接收 net::ERR_EMPTY_RESPONSE

python从特定位置读取二进制文件