Amazon S3 .NET Core如何上传文件

kos*_*tas 10 amazon-s3 asp.net-core

我想在.NET Core项目中上传一个带有Amazon S3的文件.是否有关于如何创建和使用AmazonS3客户端的参考?我在.Net Core的AmazonS3文档中找到的就是这个(http://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-config-netcore.html),这是不是很有帮助.

Tia*_*ila 24

我确实使用过IFormFile,如下所示:

(您需要安装AWSSDK.S3)

public async Task UploadFileToS3(IFormFile file)
{
    using (var client = new AmazonS3Client("yourAwsAccessKeyId", "yourAwsSecretAccessKey", RegionEndpoint.USEast1))
    {
        using (var newMemoryStream = new MemoryStream())
        {
            file.CopyTo(newMemoryStream);

            var uploadRequest = new TransferUtilityUploadRequest
            {
                InputStream = newMemoryStream,
                Key = file.FileName,
                BucketName = "yourBucketName",
                CannedACL = S3CannedACL.PublicRead
            };

            var fileTransferUtility = new TransferUtility(client);
            await fileTransferUtility.UploadAsync(uploadRequest);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Tas*_*iha 14

对于.netcore项目中的简单文件上传,我按照此链接.

完成简单的文件上传程序后,我按照这个和这个链接的文档,这是非常有帮助的.以下两个链接也有助于快速启动.

  1. https://github.com/awslabs/aws-sdk-net-samples/blob/master/ConsoleSamples/AmazonS3Sample/AmazonS3Sample/S3Sample.cs

  2. http://www.c-sharpcorner.com/article/fileupload-to-aws-s3-using-asp-net/

这是我在文件上传控制器中的最终代码片段(我跳过了视图部分,在上面分享的链接中详细解释).

[HttpPost("UploadFiles")]
public IActionResult UploadFiles(List<IFormFile> files)
{
     long size = files.Sum(f => f.Length);

     foreach (var formFile in files)
     {
           if (formFile.Length > 0)
           {
                var filename = ContentDispositionHeaderValue
                        .Parse(formFile.ContentDisposition)
                        .FileName
                        .TrimStart().ToString();
                filename = _hostingEnvironment.WebRootPath + $@"\uploads" + $@"\{formFile.FileName}";
                size += formFile.Length;
                using (var fs = System.IO.File.Create(filename))
                {
                     formFile.CopyTo(fs);
                     fs.Flush();
                }//these code snippets saves the uploaded files to the project directory

                 uploadToS3(filename);//this is the method to upload saved file to S3

            }
      }

      return RedirectToAction("Index", "Library");
}
Run Code Online (Sandbox Code Playgroud)

这是将文件上传到Amazon S3的方法:

        private IHostingEnvironment _hostingEnvironment;
        private AmazonS3Client _s3Client = new AmazonS3Client(RegionEndpoint.EUWest2);
        private string _bucketName = "mis-pdf-library";//this is my Amazon Bucket name
        private static string _bucketSubdirectory = String.Empty;

        public UploadController(IHostingEnvironment environment)
        {
            _hostingEnvironment = environment;
        }


        public void uploadToS3(string filePath)
        {
            try
            {
                TransferUtility fileTransferUtility = new
                    TransferUtility(new AmazonS3Client(Amazon.RegionEndpoint.EUWest2));

                string bucketName;


                if (_bucketSubdirectory == "" || _bucketSubdirectory == null)
                {
                    bucketName = _bucketName; //no subdirectory just bucket name  
                }
                else
                {   // subdirectory and bucket name  
                    bucketName = _bucketName + @"/" + _bucketSubdirectory;
                }


                // 1. Upload a file, file name is used as the object key name.
                fileTransferUtility.Upload(filePath, bucketName);
                Console.WriteLine("Upload 1 completed");


            }
            catch (AmazonS3Exception s3Exception)
            {
                Console.WriteLine(s3Exception.Message,
                                  s3Exception.InnerException);
            }
        }
Run Code Online (Sandbox Code Playgroud)

这只是用于在Amazon S3存储桶中上传文件.我在.netcore 2.0上工作,并且不要忘记为使用Amazon API添加必要的依赖项.这些曾经是:

  1. AWSSDK.Core
  2. AWSSDK.Extensions.NETCore.Setup
  3. AWSSDK.S3

希望,这会有所帮助.

  • 这是孟加拉国的胜利.现在女孩们可以回答堆栈.做得好.Upvoted.好答案! (5认同)

小智 7

我编写了一个完整的示例,用于使用 asp.net core mvc 将文件上传到 Amazon AWS S3

你可以在 github 链接中查看我的示例项目:

https://github.com/NevitFeridi/AWS_Upload_Sample_ASPCoreMVC

HomeController 中有一个使用 Amazon.S3 SDK 将文件上传到 S3 的功能。

在此功能“UploadFileToAWSAsync”中,您可以找到您需要的所有内容

        // you must set your accessKey and secretKey
        // for getting your accesskey and secretKey go to your Aws amazon console
        string AWS_accessKey = "xxxxxxx";
        string AWS_secretKey = "xxxxxxxxxxxxxx";
        string AWS_bucketName = "my-uswest";
        string AWS_defaultFolder = "MyTest_Folder";
      protected async Task<string> UploadFileToAWSAsync(IFormFile myfile, string subFolder = "")
        {
            var result = "";
            try
            {
                var s3Client = new AmazonS3Client(AWS_accessKey, AWS_secretKey, Amazon.RegionEndpoint.USWest2);
                var bucketName = AWS_bucketName;
                var keyName = AWS_defaultFolder;
                if (!string.IsNullOrEmpty(subFolder))
                    keyName = keyName + "/" + subFolder.Trim();
                keyName = keyName + "/" + myfile.FileName;

                var fs = myfile.OpenReadStream();
                var request = new Amazon.S3.Model.PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName,
                    InputStream = fs,
                    ContentType = myfile.ContentType,
                    CannedACL = S3CannedACL.PublicRead
                };
                await s3Client.PutObjectAsync(request);

                result = string.Format("http://{0}.s3.amazonaws.com/{1}", bucketName, keyName);
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return result;
        }


Run Code Online (Sandbox Code Playgroud)


Ozg*_*gur 5

除了@Tiago的答案之外,AWSS3 SDK也发生了一些变化,所以这里是更新的方法:

    public async Task UploadImage(IFormFile file)
    {
        var credentials = new BasicAWSCredentials("access", "secret key");
        var config = new AmazonS3Config
        {
            RegionEndpoint = Amazon.RegionEndpoint.EUNorth1
        };
        using var client = new AmazonS3Client(credentials, config);
        await using var newMemoryStream = new MemoryStream();
        file.CopyTo(newMemoryStream);

        var uploadRequest = new TransferUtilityUploadRequest
        {
            InputStream = newMemoryStream,
            Key = file.FileName,
            BucketName = "your-bucket-name",
            CannedACL = S3CannedACL.PublicRead
        };

        var fileTransferUtility = new TransferUtility(client);
        await fileTransferUtility.UploadAsync(uploadRequest);
    }
Run Code Online (Sandbox Code Playgroud)


Rya*_*eir 1

根据 AWS SDK 文档,.Net Core 支持于 2016 年底添加。

https://aws.amazon.com/sdk-for-net/

因此,将文件上传到 S3 的说明应与 .Net 的任何其他说明相同。

适用于 .Net 的 AWS 开发工具包的“入门”指南实际上就是您所描述的连接文件并将文件上传到 S3 的情况 - 如果您安装了“AWS Toolkit for Visual”,它会作为示例项目包含在内,可供您运行。 Studio”(应与 .Net AWS SDK 一起安装)。

所以你需要做的就是打开 Visual Studio,找到他们的示例 S3 项目,或者你可以在这里查看:

            // simple object put
            PutObjectRequest request = new PutObjectRequest()
            {
                ContentBody = "this is a test",
                BucketName = bucketName,
                Key = keyName
            };

            PutObjectResponse response = client.PutObject(request);
Run Code Online (Sandbox Code Playgroud)

这假设您在包含命名空间后已实例化 Amazon.S3.AmazonS3Client,并使用您自己的凭证配置它。