我正在尝试使用Typescript和aws-sdk软件包将文件上传到S3存储桶。理想的结果是: 成功上传到s3,然后=>加载SQS消息。
这里是读取接收的文件并执行s3Upload的功能
// on each byte of uploading
file.on("data", function (data) {
console.log("File [" + fieldname + "] got " + data.length + " bytes");
});
// whenever the upload is finished into this microservice
file.on("end", function () {
console.log("File [" + fieldname + "] Finished uploading");
});
const s3BucketLink = await saveToS3(filename, file);
### HERE IS IMPORTANT, I BASICALLY WANT TO CONFIRM THAT STATUS IS 200 and only then upload to SQS
if (s3BucketLink.status === 200) {
console.log("its done");
}
console.log("here");
console.log(s3BucketLink);
});
在我的saveToS3中,有这个
interface S3Response {
status: number;
filepath: string;
}
export const saveToS3 = async (filename: string, file: any): Promise<S3Response> => {
let status = {
status: 400,
filepath: ""
};
s3.listBuckets(function (err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data.Buckets);
}
});
const params = {
Bucket: bucketName,
Key: filename, // File name you want to save as in S3
Body: file
};
s3.upload(params, function (err: Error, data: any) {
if (err) {
throw err;
}
console.log(`File uploaded successfully. ${data.Location}`);
status = {
status: 200,
filepath: data.Location
};
});
return status;
};
我基本上是在尝试将状态设置为200,如果是这种情况,则继续并加载sqs。
console.log中的当前结果如下:
[Function]
File [File] got 65002 bytes
here
{ status: 400 }
File [File] got 65536 bytes
File [File] got 65536 bytes
File [File] got 65536 bytes
File [File] got 65536 bytes
File [File] got 65536 bytes
File [File] got 65536 bytes
File [File] got 65536 bytes
File [File] got 65536 bytes
File [File] got 65536 bytes
File [File] got 65536 bytes
File [File] got 43814 bytes
File [File] Finished uploading
Success [ { Name: 'name', CreationDate: 2020-05-31T06:50:22.000Z } ]
File uploaded successfully. https://name.s3.amazonaws.com/file_example_MP3_700KB.mp3
非常感谢您提供有关如何实现所需结果的帮助:)
答案 0 :(得分:1)
您似乎在这里遇到了几个问题。
您正在执行几个异步方法(s3.listBuckets
和s3.upload
),而无需等待它们完成。因此,您要开始执行这些操作,然后调用return status;
,这就是为什么您在文件上传完成之前提早获得该值的原因。您需要等待这些事情完成才能返回。
但是这两个方法都使用回调,而不是诺言,并且您希望saveToS3
方法返回一个Promise
。因此,您需要包装这两个方法调用。这是看起来像的简化示例(省略了一些代码)。在此示例中,该方法返回一个Promise
,只有在触发s3.upload
的回调时才解决,这意味着操作已完成或返回了错误。
export const saveToS3 = (filename: string, file: any): Promise<S3Response> => {
return new Promise((resolve, reject) => {
s3.upload(params, function (err: Error, data: any) {
if (err) {
return reject(err);
}
resolve(status);
});
});
}
这将导致任何await saveToS3()
语句等待操作完成。