-AWS C# .Net Core- 如何将 .jpg 图像上传到 S3 存储桶而不将其另存为文件

-AWS C# .Net Core- How to upload a .jpg image to S3 bucket without saving it as a file

我正在使用 AWS Lambda C# .Net 核心

我正在尝试上传 .jpg 文件而不将其保存到本地计算机(在已部署的 Lambda 函数中不允许)

我得到十六进制字符串形式的文件,可以将其重新编码为二进制文件,将其保存为文件,甚至可以正常从我的本地调试上传它。

int len = image.ImagePayload.Length;
byte[] bin = new byte[len / 2];
for (int i = 0; i < len; i += 2)
{
    bin[i / 2] = Convert.ToByte(image.ImagePayload.Substring(i, 2), 16);
}

File.WriteAllBytes(image.ImageName, bin);

PutObjectRequest putObj = new PutObjectRequest
{
    BucketName = input.Bucket,
    FilePath = image.ImageName,
    ContentType = "image/jpg",
    Key = image.ImageName
};
PutObjectResponse putResp = S3Client.PutObjectAsync(putObj).Result;

完全部署后,AWS Lambda 失败 "Read-only file system"

有什么方法可以在不将数据保存到文件的情况下上传到 S3?

您可以在 PutObjectRequest 上使用 InputStream 而不是 FilePath

byte bin = ...

using (var stream = new MemoryStream(bin))
{
    var request = new PutObjectRequest
    {
        BucketName = input.Bucket,
        InputStream = stream,
        ContentType = "image/jpg",
        Key = image.ImageName
    }

    var response = await S3Client.PutObjectAsync(request).ConfigureAwait(false);
}

参考:https://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/T_Amazon_S3_Model_PutObjectRequest.htm