天天看點

AWS S3 API實作檔案上傳下載下傳(ASP.NET MVC)

    近日項目需要使用AWS S3的API實作檔案的上傳和下載下傳功能,發現網上很多都是Java版本的,.NET版本很少,其中遇到了幾個小問題,在這裡寫一下友善以後大家開發。

    需要先通過Nuget下載下傳AWS S3的工具包

AWS S3 API實作檔案上傳下載下傳(ASP.NET MVC)

    1、首先加入配置,其中标紅部分是個坑,因為aws伺服器是分地區的,我這裡用的是新加坡的aws,這裡如果不配置區域會一直報錯,還找不到頭緒。

private static string awsAccessKey = "***";
        private static string awsSecretKey = "***";
        private static string bucketName = "***";
        AmazonS3Config config = new AmazonS3Config()
        {
            ServiceURL = "http://s3.amazonaws.com",
            RegionEndpoint = Amazon.RegionEndpoint.CNNorth1
        }; 
           

2.上傳代碼

 其中HttpPostedFileBase為MVC中的檔案上傳類,這裡直接通過Controller傳過來此類型,實際使用可以改一下,接收參數用Stream類型,對應的InputStream直接接收Stream類型。

public void S3Upload(HttpPostedFileBase file)  
        {  
            using (client = new AmazonS3Client(awsAccessKey, awsSecretKey, config))  
            {  
                var request = new PutObjectRequest()  
                {  
                    BucketName = bucketName,  
                    CannedACL = S3CannedACL.PublicRead,  
                    Key = string.Format("UPLOADS/{0}", file.FileName),  
                    InputStream = file.InputStream  
                };  
  
            client.PutObject(request);  
            }  
        }  
           

3.下載下傳代碼

public void S3Download()  
    {  
        using (client = new AmazonS3Client(awsAccessKey, awsSecretKey, config))  
        {  
            GetObjectRequest request = new GetObjectRequest()  
            {  
                BucketName = bucketName,  
                Key = "test"  
            };  
      
            GetObjectResponse response = client.GetObject(request);  
            response.WriteResponseStreamToFile("C:\\Users\\Documents\\test.txt");  
        }  
    }  
           

繼續閱讀