上传文件到s3桶

本文关键字:s3 文件 | 更新日期: 2023-09-27 18:13:01

我试图将我的文件上传到s3桶,但我不希望该文件从我的本地机器上传,而不是当有人使用应用程序并上传文件时,应该直接上传到我的s3桶!!有办法做到这一点吗?(代码应该在。net中)

            string filekey = filePath.Substring(filePath.LastIndexOf('''') + 1);
            using (MemoryStream filebuffer = new MemoryStream(File.ReadAllBytes(filePath)))
            {
                PutObjectRequest putRequest = new PutObjectRequest
                {
                    BucketName = this.awsBucketName,
                    Key = "GUARD1" + "/" + filekey,
                    InputStream = filebuffer,
                    ContentType = "application/pkcs8",
                };

这就是我正在做的…这反过来在桶中创建一个文件夹,并从本地机器获取文件路径,并将其上传到桶中。

我需要的是文件不应该保存在本地机器中,而是直接从应用程序到s3桶。

这是WriteIntoS3方法:

string filekey = filePath.Substring(filePath.LastIndexOf('''') + 1);
                using (MemoryStream filebuffer = new MemoryStream(File.ReadAllBytes(filePath)))
                {
                    PutObjectRequest putRequest = new PutObjectRequest
                    {
                        BucketName = this.awsBucketName,
                        Key = "GUARD1" + "/" + filekey,
                        InputStream = filebuffer,
                        ContentType = "application/pkcs8",
                    };
                    client.PutObject(putRequest);
                    GetPreSignedUrlRequest expiryUrlRequest = new GetPreSignedUrlRequest();
                    expiryUrlRequest.BucketName = this.awsBucketName;
                    expiryUrlRequest.Key = filekey;
                    expiryUrlRequest.Expires = DateTime.Now.AddDays(ExpiryDays);
                    string url = client.GetPreSignedURL(expiryUrlRequest);
                    return url;
                }

上传文件到s3桶

如果你不想使用本地文件,那么你可以使用TransferUtility类直接上传流到S3。

例如:

using Amazon.S3.Transfer;
using System.IO;
class Program
{
    static void Main(string[] args)
    {
        var client = new Amazon.S3.AmazonS3Client();
        using (var ms = new MemoryStream()) // Load the data into memorystream from a data source other than a file
        {
            using (var transferUtility = new TransferUtility(client))
            {
                transferUtility.Upload(ms, "bucket", "key");
            }
        }
    }
}