天天看点

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");  
        }  
    }  
           

继续阅读