使用Axios下载文件,然后上传到Amazon S3 [英] Downloading File using Axios then uploading to Amazon S3

查看:25
本文介绍了使用Axios下载文件,然后上传到Amazon S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在上看到了关于使用Axios下载文件并将其上传到S3的各种问题,但没有一个问题将它们联系在一起,我对流、BLOB、多部分表单等感到困惑。以下是我到目前为止的代码。

正在下载文件。

const downloadResponse = await axios({
    url: `https://example.com/test.jpg`,
    method: 'GET',
    responseType: 'stream'   // Should this be blob, stream or arraybuffer?
})

不确定";downloadResponse.data";中包含的内容,此时类型表明它是对象,而不是流

获取签名响应(这是通过Storyblok CMS而不是Amazon完成的)

const signedResponse = await axios.post(`https://api.storyblok.com/v1/spaces/xxx/assets`, {
    filename: 'test.jpg',
}, {
    headers: {'Authorization': 'xxxxx'}
})

使用Form-Data Package创建表单数据

let form = new FormData()

for (var key in signedResponse.fields) {
    form.append(key, signedResponse.fields[key])
}

try {
    form.append('file', fs.createReadStream(downloadResponse.data))
} catch (error) {
    console.log("Error Creating Data", error)
}

上载到S3

try {
    
    const uploadResponse = await axios({
        method: 'post',
        url: signedResponse .data.post_url,
        data: form.getBuffer(),
        headers: form.getHeaders()
    })

} catch (error) {
    console.log("Error Uploading", error)
}

目前,这导致在创建流时出现以下错误。

创建数据类型错误[ERR_INVALID_ARG_TYPE]时出错:";路径&必须是字符串、缓冲区或URL类型之一。收到类型对象。

我尝试直接从第一个请求中获取数据,但没有对其使用fs.createReadStream(),因为它应该已经是流,但这产生了相同的错误。

我还尝试从第一个请求返回一个arrayBuffer,并使用Buffer.from(),然后附加缓冲区,但也没有成功,我想Amazon给了我一个400错误,所以我迷路了。

如有任何帮助,我们将不胜感激。

推荐答案

此代码使用v3版本的AWS JS SDK。使用节点v16(ES16模块)

  1. 初始化S3客户端
// Ref: https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/index.html
import { S3Client } from '@aws-sdk/client-s3';

// Constants
const accessKeyId = process.env.AWS_ACCESS_KEY
const secretAccessKey = process.env.AWS_SECRET_KEY
const awsRegion = 'ap-south-1';
export const awsBucket = process.env.AWS_BUCKET;

export const S3 = new S3Client({
  credentials: {
    accessKeyId,
    secretAccessKey,
  },
  region: awsRegion,
});
  1. 使用Axios下载。
    最重要的部分是使用responseType: 'arraybuffer'
const resp = await axios.get('https://domain/image/imagename.png', {   
  decompress: false,
  // Ref: https://stackoverflow.com/a/61621094/4050261
  responseType: 'arraybuffer',
})
  1. 使用S3客户端上传
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { awsBucket, S3 } from '../lib/aws.js'; // Defined in Point 1 above

await S3.send(
  new PutObjectCommand({
    Bucket: awsBucket,
    Key: `foldername/filename`,
    Body: resp.data,
  })
)

这篇关于使用Axios下载文件,然后上传到Amazon S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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