【发布时间】: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