简体   繁体   English

使用 nodeJS 从 Amazon S3 读取文件并使用 axios 将其发布到另一台服务器

[英]Read file from Amazon S3 with nodeJS and post it to another server with axios

Im trying to read a file (image) from amazon S3 and post it to another server with multipart/form .我试图从亚马逊 S3 读取文件(图像)并将其发布到另一台带有multipart/form服务器。

  let imageParams = { Bucket: 'my-bucket', Key: 'imageName.jpg' };

  let formData = new FormData();

  formData.append('file', s3.getObject(imageParams).createReadStream());

  let apiResponse = await api.post("/fileUpload", formData,
    { params: { token: process.env.API_TOKEN } }, 
    { headers: {'Content-Type': 'multipart/form-data' } } );

But im not managing it to work, it returns me:但我没有管理它工作,它返回给我:

Error: Request failed with status code 415

maybe im misunderstanding how the createReadStream() works?也许我误解了createReadStream()是如何工作的?

Use concat for pipe the stream.使用 concat 对流进行管道传输。 Otherwise form data send only the first chunk of stream, and the server don't know how to handle it.否则表单数据只发送流的第一个块,服务器不知道如何处理它。

For example例如

const axios = require('axios');
const {S3} = require('aws-sdk');
const FormData = require('form-data');
const s3 = new S3();
var concat = require('concat-stream')

const api = axios.default.create({
    baseURL: 'http://example.com',

})

const readStream = s3.getObject({Bucket: 'bucket', Key: 'file'}).createReadStream();
readStream.pipe(concat(filebuffer => {
    const formData = new FormData();
    formData.append('file', filebuffer);
    formData.getLength((err, length) => {
        console.log(length)
        const headers = formData.getHeaders({'content-length': length})
        console.log({headers})
        return api({
            method: 'post',
            url: "/upload",
            headers: headers,
            data: formData
        })
    })

}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM