使用C#将文件添加到AmazonS3上的bucket中

本文关键字:AmazonS3 上的 bucket 添加 文件 使用 | 更新日期: 2023-09-27 18:00:27

如何将位图对象作为图像保存到AmazonS3?

我已经完成了所有的设置,但我有限的C sharp阻止了我完成这项工作。

// I have a bitmap iamge
Bitmap image = new Bitmap(width, height);
// Rather than this
image.save(file_path);
// I'd like to use S3
S3 test = new S3();
test.WritingAnObject("images", "testing2.png", image);
// Here is the relevant part of write to S3 function
PutObjectRequest titledRequest = new PutObjectRequest();
titledRequest.WithMetaData("title", "the title")
             .WithContentBody("this object has a title")
             .WithBucketName(bucketName)
             .WithKey(keyName);

正如您所看到的,S3函数只能接收一个字符串并将其保存为文件的主体。

我怎么能这样写,它将允许我传入位图对象并将其保存为图像?也许是一条小溪?还是作为字节数组?

我感谢你的帮助。

使用C#将文件添加到AmazonS3上的bucket中

您可以使用WithInputStreamWithFilePath。例如,将新图像保存到S3:

using (var memoryStream = new MemoryStream())
{
    using(var yourBitmap = new Bitmap())
    {
        //Do whatever with bitmap here.
        yourBitmap.Save(memoryStream, ImageFormat.Jpeg); //Save it as a JPEG to memory stream. Change the ImageFormat if you want to save it as something else, such as PNG.
        PutObjectRequest titledRequest = new PutObjectRequest();
        titledRequest.WithMetaData("title", "the title")
            .WithInputStream(memoryStream) //Add file here.
            .WithBucketName(bucketName)
            .WithKey(keyName);
    }
}

设置请求对象的InputStream属性:

titledRequest.InputStream = image;