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

时间:2019-06-28 20:49:26

标签: c# amazon-s3 aws-lambda image-uploading

我正在使用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完全部署后会失败,并显示“只读文件系统”

是否可以在不将数据保存到文件的情况下上传到S3?

1 个答案:

答案 0 :(得分:2)

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

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