.NETCore AWS S3操作

获取预签名URL,可以用来回显(共享对象),上传文件用

如果是图片和视频回显,获取方式用Get,直接绑定src=预签名url就可以回显,如果是需要上传,那么预签名URL的获取方式要用PUT ,

public string GeneratePreSignedURL(string path)
{
    var request = new GetPreSignedUrlRequest
    {
        BucketName = bucketName,
        Key = path,
        //上传时用PUT
        //Verb = HttpVerb.PUT,
        //回显图片视频用Get,默认是GET
        Verb = HttpVerb.GET,
        //Expires = DateTime.Now.AddMinutes(200),
        Expires = DateTime.Now.AddMinutes(60),

        //ContentType = "binary/octet-stream"//must add this parameter
    };
    return s3Client.GetPreSignedURL(request);
}

请参考 使用预签名 URL 共享对象 - Amazon Simple Storage Service

 

S3对象的初始化,为了调用各种S3方法用

S3桶为了安全一般都设置成私有的,这种方式可以共享,上传对象,我是在构造里初始化好s3Client对象

public const string bucketName = "***bucket123";
public string accessKeyID = "AKIARLS***BT3HZAY";
public string secretKey = "R+WS7ul5BANYfpu***TPhGV1tv";

public IAmazonS3 s3Client;

public S3Demo()
{
    AmazonS3Config config = new AmazonS3Config()
    {
        ServiceURL = "http://s3.amazonaws.com",
        RegionEndpoint = Amazon.RegionEndpoint.USEast1
    };
    //AWSCredentials credentials;
    //credentials = new BasicAWSCredentials(accessKeyID, secretKey);
    s3Client = new AmazonS3Client(accessKeyID, secretKey, config);
}

获取文件夹下所有文件(包括子文件夹)的key,为了删文件夹下所有文件以及子文件遍历用

/// 
/// Get objects under the specified folder in the Amazon S3 bucket.
/// 
/// The specified folder in the Amazon S3 bucket.
/// S3Objects list
public List GetFilesByFolder(string folderName)
{
    ListObjectsV2Request request = new()
    {
        BucketName = bucketName,
        Prefix = folderName
    };
    ListObjectsV2Response response = new();
    List fileNames = new();

    do
    {
        response = client.ListObjectsV2Async(request).GetAwaiter().GetResult();
        response.S3Objects.ForEach(obj => fileNames.Add(obj));
    }
    while (response.IsTruncated);

    return fileNames;
}

获取文件的二进制(字节数组),可以下载文件转流用

public async Task ReadObjectDataAsync(string keyName)
{
    try
    {
        GetObjectRequest request = new GetObjectRequest
        {
            BucketName = bucketName,
            Key = keyName
        };
        ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
        responseHeaders.CacheControl = "No-cache";
        request.ResponseHeaderOverrides = responseHeaders;
        using (GetObjectResponse response = await client.GetObjectAsync(request))
        using (Stream responseStream = response.ResponseStream)
        using (MemoryStream memStream = new MemoryStream())
        {
            responseStream.CopyTo(memStream);
            memStream.Seek(0, SeekOrigin.Begin);
            byte[] bytes = memStream.ToArray();
            return bytes;
        }
    }
    catch (AmazonS3Exception e)
    {
        // If bucket or object does not exist
        Console.WriteLine("Error encountered ***. Message:'{0}' when reading object", e.Message);
        return null;
    }
    catch (Exception e)
    {
        Console.WriteLine("Unknown encountered on server. Message:'{0}' when reading object", e.Message);
        return null;
    }
}

仅供学习参考,如有侵权联系我删除

你可能感兴趣的:(aws,.netcore,云计算)