NodeJS 如何将base64编码文件中的缓冲区上传到Amazon S3?

e7arh2l6  于 2023-06-29  发布在  Node.js
关注(0)|答案(2)|浏览(140)

我正在尝试将在React Native中选择的PDF上传到Amazon s3。为此,我将用base64编码的PDF发送到我的nodejs/adonis服务器,并将其转换为缓冲区(因为我不想将其保存为base64)。
PDF实际上是保存在我的S3桶,但不正确,因为我既不能打开它,也不能下载它。
我就是这么做的

public async storeFile({ request }: HttpContextContract) {

    const hash = crypto.randomBytes(32).toString('hex');
    let key = `PDF-${hash}`;
    //create a single key for each file

    const file = request.input('file');
    const fileBuffer = Buffer.from(file, 'base64');
    //transform the file encoded in base64 into a buffer

    await S3Service.uploadManually2(fileBuffer, key);

  }
public async uploadManually2(file: Buffer, key: string): Promise<string> {

    const params = {
      Bucket: Env.get('AWS_BUCKET_NAME'),
      Body: file,
      Key: key,
      ContentType: 'application/pdf',
      ACL: 'public-read',
    }
    await s3.send(new PutObjectCommand(params))

    const url = `https://${Env.get('AWS_BUCKET_NAME')}.s3.amazonaws.com/${key}`
    return url
  }
gz5pxeao

gz5pxeao1#

这里最简单的解决方法是将PDF文件的缓冲区形式转换为可读流,然后将该流传递给S3。

// Add the following import on your module
const { Readable } = require('stream');

public async storeFile({ request }: HttpContextContract) {

     const hash = crypto.randomBytes(32).toString('hex');
     let key = `PDF-${hash}`;

     const file = request.input('file');
     const fileBuffer = Buffer.from(file, 'base64');
     const stream = new Readable();

     stream.push(fileBuffer)   
     stream.push(null);

     await S3Service.uploadManually2(stream, key);
}

public async uploadManually2(stream: Stream, key: string): Promise<string> {
    const params = {
      Bucket: Env.get('AWS_BUCKET_NAME'),
      Body: stream,
      Key: key,
      ContentType: 'application/pdf',
      ACL: 'public-read',
    }
    await s3.send(new PutObjectCommand(params))

    const url = `https://${Env.get('AWS_BUCKET_NAME')}.s3.amazonaws.com/${key}`
    return url
  }
wbrvyc0a

wbrvyc0a2#

我最初的目标是从react-native发送一个PDF到S3。首先,我尝试将文件发送到服务器,然后发送到s3,但对我来说,它的工作方式是从react-native直接发送到s3。为此,我安装了库“react-native-aws 3”并使用函数“put”。
这是我使用的代码:

import { RNS3 } from "react-native-aws3"

async function enviaPdfS3(uri, fileName){

  const chave = `PDF-${(Math.random() * 100).toString()}-${fileName}`
  //create a single key for each file

  const file = {
    uri: uri,
    name: key,
    type: 'application/pdf'
  }

  const options = {
    bucket: INSERT YOUR BUCKET'S NAME,
    region: INSERT YOUR BUCKET'S REGION,
    accessKey: INSERT YOUR BUCKET'S ACCESS KEY,
    secretKey: INSERT YOUR BUCKET'S SECRET KEY,
    successActionStatus: 201
  }

  await RNS3.put(file, options)

}

相关问题