【问题标题】:Uploading files with Koa and Typescript to S3 compatible Storage使用 Koa 和 Typescript 将文件上传到 S3 兼容存储
【发布时间】:2020-02-28 12:47:36
【问题描述】:

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

错误:TS2345 端点类型参数 '{endpoint: Endpoint; accessKeyId: string;}' 不可分配给类型参数 '客户端配置'。

我已经忽略了 @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 })
        }
      }
    )
  })
}

【问题讨论】:

    标签: node.js typescript amazon-s3 koa


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果您使用 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

      【讨论】:

      • 上传时可以传递bucketname。那不是我的问题。
      猜你喜欢
      • 1970-01-01
      • 2020-06-27
      • 2018-04-25
      • 2020-08-31
      • 2018-08-31
      • 2023-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多