简体   繁体   中英

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

I'm using AWS Lambda C# .Net core

I am trying to upload a .jpg file without saving it to the local machine (not allowed in a deployed Lambda function)

I get the file in hex-string form and can re-code it into binary, save it as a file, and even upload it from my local debug normally.

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 fails with "Read-only file system" when fully deployed

Any way to upload to S3 without saving the data to a file?

Instead of using FilePath , you can use InputStream on the 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);
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM