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

Uploading files with Koa and Typescript to S3 compatible Storage

我正在尝试将图像从 Stackpath 上传到 S3 兼容存储。我正在使用 Koa 和打字稿。我在 medium 上找到了一个例子。 我发现了多个问题,我不确定如何声明键的类型,url 和文件名、文件路径和文件类型。 此外,变量端点不可分配给字符串类型的 属性。

Error: TS2345 Argument of type endpoint '{endpoint: Endpoint; accessKeyId: string;}' is not assignable to parameter of type 'ClientConfiguration'.

我已经忽略了@ts-ignore 的这个问题,但想修复它们。 即使我忽略了这个问题来尝试使用代码并用邮递员发送图像,file.name 等等都是未定义的。

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 })
        }
      }
    )
  })
}

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

javascript 示例:

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

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

See :

Here's AWS Document

问题是我使用了 koa-body。 Koa mulder 解决了我的问题。 如果你使用 form-data,就使用 Koa mulder 作为中间件。