如何使用c#将文件上传到亚马逊S3超级简单

时间:2014-09-12 18:56:05

标签: c# .net amazon-s3

我厌倦了所有这些"上传到S3"不起作用的示例和教程,有人可以向我展示一个简单有效的例子吗?

6 个答案:

答案 0 :(得分:51)

以下是您必须遵循的说明才能获得完整的演示程序...

1 - 下载并安装可在(http://aws.amazon.com/sdk-for-net/)中找到的适用于.NET的Amazon Web服务SDK。因为我有visual studio 2010我选择安装3.5 .NET SDK。

2-开放视觉工作室并制作一个新项目,我有visual studio 2010,我正在使用控制台应用程序项目。

3-添加对AWSSDK.dll的引用,它与上面提到的Amazon Web服务SDK一起安装,在我的系统中,dll位于“C:\ Program Files(x86)\ AWS SDK for .NET \ bin \ Net35 \ AWSSDK.dll”。

4-制作一个新的类文件,在这里称它为“AmazonUploader”类的完整代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;

namespace UploadToS3Demo
{
    public class AmazonUploader
    {
        public bool sendMyFileToS3(string localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
        {
        // input explained :
        // localFilePath = the full local file path e.g. "c:\mydir\mysubdir\myfilename.zip"
        // bucketName : the name of the bucket in S3 ,the bucket should be alreadt created
        // subDirectoryInBucket : if this string is not empty the file will be uploaded to
            // a subdirectory with this name
        // fileNameInS3 = the file name in the S3

        // create an instance of IAmazonS3 class ,in my case i choose RegionEndpoint.EUWest1
        // you can change that to APNortheast1 , APSoutheast1 , APSoutheast2 , CNNorth1
        // SAEast1 , USEast1 , USGovCloudWest1 , USWest1 , USWest2 . this choice will not
        // store your file in a different cloud storage but (i think) it differ in performance
        // depending on your location
        IAmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.EUWest1);

        // create a TransferUtility instance passing it the IAmazonS3 created in the first step
        TransferUtility utility = new TransferUtility(client);
        // making a TransferUtilityUploadRequest instance
        TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();

        if (subDirectoryInBucket == "" || subDirectoryInBucket == null)
        {
            request.BucketName = bucketName; //no subdirectory just bucket name
        }
        else
        {   // subdirectory and bucket name
            request.BucketName = bucketName + @"/" + subDirectoryInBucket;
        }
        request.Key = fileNameInS3 ; //file name up in S3
        request.FilePath = localFilePath; //local file name
        utility.Upload(request); //commensing the transfer

        return true; //indicate that the file was sent
    }
  }
}

5-添加配置文件:在解决方案资源管理器中右键单击您的项目,然后选择“添加” - >然后从列表中选择“新建项目”,选择“应用程序配置文件”类型,然后单击“添加”按钮。一个名为“App.config”的文件被添加到解决方案中。

6-编辑app.config文件:双击解决方案资源管理器中的“app.config”文件,将出现编辑菜单。用以下文字替换所有文本:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="AWSProfileName" value="profile1"/>
    <add key="AWSAccessKey" value="your Access Key goes here"/>
    <add key="AWSSecretKey" value="your Secret Key goes here"/>

  </appSettings>
</configuration>

您必须修改上述文字以反映您的亚马逊访问密钥ID和秘密访问密钥。

7-现在在program.cs文件中(记住这是一个控制台应用程序)编写以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UploadToS3Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // preparing our file and directory names
            string fileToBackup = @"d:\mybackupFile.zip" ; // test file
            string myBucketName = "mys3bucketname"; //your s3 bucket name goes here
            string s3DirectoryName = "justdemodirectory";
            string s3FileName = @"mybackupFile uploaded in 12-9-2014.zip";

            AmazonUploader myUploader = new AmazonUploader();
            myUploader.sendMyFileToS3(fileToBackup, myBucketName, s3DirectoryName, s3FileName);
        }
    }
}

8-用您自己的数据替换上面代码中的字符串

9-添加纠错 并且你的程序准备好了

答案 1 :(得分:38)

@docesam的解决方案适用于旧版本的AWSSDK。 以下是AmazonS3最新文档的示例:

1)首先打开Visual Studio(我使用VS2015)并创建一个新项目 - &gt; ASP.NET Web应用程序 - &gt; MVC。

2)浏览Manage Nuget Package,包 AWSSDK.S3 并安装它。

3)现在创建一个名为AmazonS3Uploader的类,然后复制并粘贴此代码:

using System;
using Amazon.S3;
using Amazon.S3.Model;

namespace AmazonS3Demo
{
    public class AmazonS3Uploader
    {
        private string bucketName = "your-amazon-s3-bucket";
        private string keyName = "the-name-of-your-file";
        private string filePath = "C:\\Users\\yourUserName\\Desktop\\myImageToUpload.jpg"; 

        public void UploadFile()
        {
            var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);

            try
            {
                PutObjectRequest putRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName,
                    FilePath = filePath,
                    ContentType = "text/plain"
                };

                PutObjectResponse response = client.PutObject(putRequest);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                    ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    throw new Exception("Check the provided AWS Credentials.");
                }
                else
                {
                    throw new Exception("Error occurred: " + amazonS3Exception.Message);
                }
            }
        }
    }
}

4)编辑您的Web.config文件,添加<appSettings></appSettings>内的下一行:

<add key="AWSProfileName" value="any name for your profile"/>
<add key="AWSAccessKey" value="your Access Key goes here"/>
<add key="AWSSecretKey" value="your Secret Key goes here"/>

5)现在从 HomeController.cs 调用您的方法UploadFile来测试它:

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            AmazonS3Uploader amazonS3 = new AmazonS3Uploader();

            amazonS3.UploadFile();
            return View();
        }
    ....

6)在您的Amazon S3存储桶中找到您的文件。

Download my Demo Project

答案 2 :(得分:0)

我最近一直在使用WinSCP,它直接连接到Amazon S3。非常简单,例如FTP。

答案 3 :(得分:0)

@ mejiamanuel57的解决方案适用于15MB以下的小文件。对于较大的文件,我得到了System.Net.Sockets.SocketException: The I/O operation has been aborted because of either a thread exit or an application request。以下改进的解决方案适用于较大的文件(已测试50MB文件):

...
public void UploadFile()
{
    var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
    var transferUtility = new TransferUtility(client);

    try
    {
        TransferUtilityUploadRequest transferUtilityUploadRequest = new TransferUtilityUploadRequest
        {
            BucketName = bucketName,
            Key = keyName,
            FilePath = filePath,
            ContentType = "text/plain"
        };

        transferUtility.Upload(transferUtilityUploadRequest); // use UploadAsync if possible
    }
...

更多信息CODE

答案 4 :(得分:0)

我为此写了tutorial

使用低级API将文件上传到S3存储桶:

IAmazonS3 client = new AmazonS3Client("AKI...access-key...", "+8Bo...secrey-key...", RegionEndpoint.APSoutheast2);  

FileInfo file = new FileInfo(@"c:\test.txt");  
string destPath = "folder/sub-folder/test.txt";
PutObjectRequest request = new PutObjectRequest()  
{  
    InputStream = file.OpenRead(),  
    BucketName = "my-bucket-name",  
    Key = destPath // <-- in S3 key represents a path  
};  

PutObjectResponse response = client.PutObject(request); 

使用高级API将文件上传到S3存储桶:

IAmazonS3 client = new AmazonS3Client("AKI...access-key...", "+8Bo...secrey-key...", RegionEndpoint.APSoutheast2);  

FileInfo localFile = new FileInfo(@"c:\test.txt");  
string destPath = @"folder\sub-folder\test.txt";  

S3FileInfo s3File = new S3FileInfo(client, "my-bucket-name", destPath);  
if (!s3File.Exists)  
{  
    using (var s3Stream = s3File.Create()) // <-- create file in S3  
    {  
        localFile.OpenRead().CopyTo(s3Stream); // <-- copy the content to S3  
    }  
}  

答案 5 :(得分:0)

AWS网站上的示例对我有用: https://docs.aws.amazon.com/AmazonS3/latest/dev/HLuploadFileDotNet.html

尽管已将其设置为返回错误的其他区域:

///私有静态只读RegionEndpoint bucketRegion = RegionEndpoint.USWest2; 私有静态只读RegionEndpoint bucketRegion = RegionEndpoint.USWest1;

我在北加州USWest1设置了水桶。