将Koa和Typescript文件上传到S3兼容存储中

问题描述 投票:0回答:2

我正在尝试将图像从Stackpath上传到S3兼容存储。我正在使用Koa和Typescript。我在媒体上找到了一个例子。我发现了多个问题,不确定如何声明密钥,URL和fileName,filePath和fileType的类型。同样,变量端点不能分配给字符串类型的属性。

错误:TS2345类型为终结点'{endpoint:Endpoint;accessKeyId:string;}'不能分配给类型的参数'ClientConfiguration'。

我已经忽略了@ ts-ignore的问题,但想修复它们。即使我忽略了这个问题,也尝试给代码尝试发送带有邮递员的图像,文件名等均未定义。

import fs from 'fs'
import { BaseContext } from 'koa'
import aws from 'aws-sdk'

const accessKeyId = '***********************'
const secretAccessKey = '*************************'

const bucketName = 'img-example'
const endpoint = new aws.Endpoint('s3.eu-central.stackpathstorage.com')

export async function upload(ctx: BaseContext) {
  const file = ctx.request.files.file
  const { key, url } = await _upload({
    fileName: file.name,
    filePath: file.path,
    fileType: file.type
  })
  ctx.body = { key, url }
}

function _upload({ fileName, filePath, fileType }) {
  return new Promise((resolve, reject) => {
    const s3 = new aws.S3({
      endpoint,
      accessKeyId,
      secretAccessKey
    })

    const stream = fs.createReadStream(filePath)
    stream.on('error', function(err) {
      reject(err)
    })

    s3.upload(
      {
        ACL: 'public-read',
        // You'll input your bucket name here
        Bucket: bucketName,
        Body: stream,
        Key: fileName,
        ContentType: fileType
      },
      function(err: any, data: { Key: any; Location: any }) {
        if (err) {
          reject(err)
        } else if (data) {
          resolve({ key: data.Key, url: data.Location })
        }
      }
    )
  })
}
node.js typescript amazon-s3 koa
2个回答
0
投票

如果使用aws-sdk的s3,则存储区名称应包含在s3变量中。

javascript示例:

const accessKeyId = '***********************'
const secretAccessKey = '*************************'
const bucketName = 'img-example'

const s3 = new AWS.S3({
  accessKeyId,
  secretAccessKey
  params: { Bucket: bucketName }
});

请参阅:

这里是AWS Document


0
投票

问题是我用了koa-body。 Koa mulder解决了我的问题。如果您使用表格数据,只需将Koa mulder用作中间件。

© www.soinside.com 2019 - 2024. All rights reserved.