如何通过multer将保存在内存中的文件上传到另一个API [英] how to upload file saved in memory by multer to another API

查看:212
本文介绍了如何通过multer将保存在内存中的文件上传到另一个API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2个单独的NodeJS API ,它们使用 multer 保存文件在内存中.

I have 2 separate NodeJS APIs that uses multer to save a file in memory.

我的快速中间件看起来像这样

My express middleware looks like this

import multer from 'multer';
const storage = multer.memoryStorage();

export default multer({ storage }).single('image');

我能够成功接收保存在内存中的文件,所以我的 req.file.image 看起来像这样

I am able to receive the file which is saved in memory successfully so my req.file.image looks like this

{ 
  fieldname: 'image',
  originalname: 'image-2017-08-28-13-47-31-218.png',
  encoding: '7bit',   mimetype: 'image/png',
  buffer: <Buffer 89 50 4e 47 0d 0a 1a 0 ... >, 
  size: 493181
}

在收到文件后,在第一个 API上,我需要将其发送到也使用 multer & 表达

After receiving the file, on the first API, I need to send it to the second API that also uses multer & express

function secondApiReceiveImage(req, res) {
  console.log(req.file)
  console.log(req.files)
  console.log(req.body)
  res.send('ok');
}

我尝试使用以下实现进行发送

I tried sending using the following implementations

通过 https://github.com/request/request#multipartform -data-multipart-form-uploads

import request from 'request';

function firstApiReceiveImage(req, res) {
  const options = {
    url:'http://SECOND_API/api/image',
    formData: { image: req.file.buffer }
  };
  request.post(options, (err, httpResponse, body) => {
    console.log('err', err);
    console.log('body', body);
  });
}

在这种情况下,要求文件要求文件要求正文的日志都是 未定义的 secondApiReceiveImage API处理函数

In this case, logs of req.file, req.files and req.body are all undefined on secondApiReceiveImage API handler function

我的下一个尝试是使用 https://github.com/form-data/form-data

My next try was with https://github.com/form-data/form-data

import multer from 'multer';
const storage = multer.memoryStorage();

export default multer({ storage }).single('image');

function firstApiReceiveImage(req, res) {
  const CRLF = '\r\n';
  const form = new FormData();
  const opts = {
    header: `${CRLF} + '--' + ${form.getBoundary()} + ${CRLF} + 'X-Custom-Header: 123' + ${CRLF} + ${CRLF}`,
    knownLength: 1
  };

  form.append('image', req.file.image.buffer, opts);
  form.submit('http://SECOND_API/api/image', (err, res) => {
    console.log('err', err);
    console.log('res', res);
  });
}

对于 req.file req.files 和<第二个API上的 req.body

除了multer BTW之外,这是我针对这两个API的中间件

These are my middlewares for both APIs aside from multer BTW

app.use(compression());
app.use(helmet());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

如果我可以将文件保留在第一个API 上,本来可以让生活更轻松,但是在这种情况下,我们不允许保存到磁盘:(

I could have had an easier life if I can persist the file on the first API, but we are not allowed to save to disk in this case :(

对我有什么建议吗?

推荐答案

通过将缓冲区首先转换为Stream并以不同的方式发送表单数据,该团队得以解决.

The team was able to get through this by converting the buffer to Stream first and send form data differently.

import stream from 'stream';
import rq from 'request-promise';

const { Duplex } = stream;

function bufferToStream(buffer) {
  const duplexStream = new Duplex();
  duplexStream.push(buffer);
  duplexStream.push(null);
  return duplexStream;
}

async function store({
  originalname, mimetype, size, buffer,
}) {
  logger.debug(`Saving image name:${originalname} type:${mimetype} size:${size}`);

  const formData = {
    image: {
      value: bufferToStream(buffer),
      options: {
        filename: originalname,
        contentType: mimetype,
        knownLength: size,
      },
    },
  };

  const options = Object.assign({}, IMAGE_SAVE_ENDPOINT, { formData });
  const response = await rq(options);
  return response.id;
}

这篇关于如何通过multer将保存在内存中的文件上传到另一个API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆