6. 文件管理

在NOS中,用户可以通过一系列的接口管理桶(Bucket)中的文件(Object),比如ListObjects,DeleteObject,CopyObject,DoesObjectExist等。

6.1. 列出桶中的文件

您可以使用AmazonS3Client.ListObjects列出存储中间中的文件:

public void ListObjects(string bucketName){
    try
    {
        var keys = new List<string>();
        ListObjectsResponse result = null;
        string nextMarker = string.Empty;
        do
        {
            var listObjectsRequest = new ListObjectsRequest()
            {
                BucketName = bucketName,
                Marker = nextMarker,
                MaxKeys = 5
            };
            result = s3Client.ListObjects(listObjectsRequest);

            foreach (var obj in result.S3Objects)
            {
                Console.WriteLine(obj.Key);
            }

            nextMarker = result.NextMarker;
        } while (result.IsTruncated);

        Console.WriteLine("List objects of bucket:{0} succeeded ", bucketName);
    }
    catch (AmazonS3Exception ex)
    {
        Console.WriteLine("Failed with HTTPStatus: {0}; \nErrorCode: {1}; \nErrorMessage: {2}; \nRequestID:{3};",
            ex.StatusCode, ex.ErrorCode, ex.Message, ex.RequestId);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
}

上述代码中的ListObjectsRequest中的可选参数如下所示:

参数 说明
Delimiter 用于对Object名字进行分组的字符。所有名字包含指定的前缀且第一次出现delimiter字符之间的object作为一组元素。限制长度为10。
Prefix 限定返回的object key必须以prefix作为前缀。注意使用prefix查询时,返回的key中仍会包含prefix
MaxKeys 限定此次返回object的最大数,如果不设定,默认为100
Marker 设定结果从marker之后按字母排序的第一个开始返回

Note

  1. 上述表中的参数都是可选参数

6.2. 判断文件是否存在

您可以使用AmazonS3Client.GetObjectMetadata的返回值来判断文件是否存在:

public bool DoesObjectExist(string bucketNaame,string key){
    try
    {
        var response = s3Client.GetObjectMetadata(new GetObjectMetadataRequest(){
            BucketName = bucketNaame,
            Key = key
        });

        return true;
    }
    catch (Amazon.S3.AmazonS3Exception ex)
    {
        if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
            return false;
    }
    return false;
}

6.3. 删除单个文件

您可以使用AmazonS3Client.DeleteObject删除单个需要删除的文件:

public void DeleteObject(string bucketNaame, string key)
{
    try
    {
        var resp = s3Client.DeleteObject(bucketNaame,key);
        Console.WriteLine("StatusCode : {0}", resp.HttpStatusCode);
    }
    catch (AmazonS3Exception ex)
    {
        Console.WriteLine("Failed with HTTPStatus: {0}; \nErrorCode: {1}; \nErrorMessage: {2}; \nRequestID:{3};",
            ex.StatusCode, ex.ErrorCode, ex.Message, ex.RequestId);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
}

6.4. 删除多个文件

您可以使用AmazonS3Client.DeleteObjects批量删除文件:

public void DeleteObjects(string bucket)
{
    try
    {
        var keys = new List<KeyVersion>();
        var listObjectsResult = s3Client.ListObjects(bucket);
        foreach (var obj in listObjectsResult.S3Objects)
        {
            keys.Add(new KeyVersion(){
                Key = obj.Key
            });
        }
        keys.Add(new KeyVersion()
        {
            Key = "NotExist" //不存在的key
        });
        var result = s3Client.DeleteObjects(new DeleteObjectsRequest(){
            BucketName = bucket,
            Objects = keys,
            Quiet=false
        });

        Console.WriteLine("Delete objects succeeded");


    }
    catch (DeleteObjectsException ex)
    {
        var resp = ex.Response;
        Console.WriteLine("No. of objects successfully deleted = {0}", resp.DeletedObjects.Count);
        Console.WriteLine("No. of objects failed to delete = {0}", resp.DeleteErrors.Count);
        foreach (DeleteError deleteError in resp.DeleteErrors)
        {
            Console.WriteLine("Error Object Key: {0}\t{1}\t{2}", deleteError.Key, deleteError.Code, deleteError.Message);
        }
        foreach (var deleteError in resp.DeletedObjects)
        {
            Console.WriteLine("Object Key: {0}", deleteError.Key);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
}

6.5. 拷贝文件

您可以使用AmazonS3Client.CopyObject拷贝文件:

public void CopyObject(string sourceBucket, string sourceKey, string targetBucket, string targetKey)
{
    try
    {
        var request = new CopyObjectRequest(){
            SourceBucket = sourceBucket,
            SourceKey = sourceKey,
            DestinationBucket = targetBucket,
            DestinationKey = targetKey
        };
        s3Client.CopyObject(request);

        Console.WriteLine("Copy object succeeded");
    }
    catch (AmazonS3Exception ex)
    {
        Console.WriteLine("Failed with HTTPStatus: {0}; \nErrorCode: {1}; \nErrorMessage: {2}; \nRequestID:{3};",
            ex.StatusCode, ex.ErrorCode, ex.Message, ex.RequestId);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
}

Attention

  1. 支持跨桶的文件copy

6.6. 获取文件的文件元信息

您可以使用AmazonS3Client.GetObjectMetadata获取对象的元数据信息:

public void GetObjectMetadata(string bucket, string key)
{
    try
    {
        var objectMetadata = s3Client.GetObjectMetadata(bucket, key);
        Console.WriteLine("Get Object Metadata succeeded");
    }
    catch (AmazonS3Exception ex)
    {
        Console.WriteLine("Failed with HTTPStatus: {0}; \nErrorCode: {1}; \nErrorMessage: {2}; \nRequestID:{3};",
            ex.StatusCode, ex.ErrorCode, ex.Message, ex.RequestId);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
}

6.7. 生成私有对象可下载的URL链接

您可以使用AmazonS3Client.GetPreSignedURL获取对象的下载URL:

public void GetObjectDownloadURL(string bucket, string key){
    try
    {
        GetPreSignedUrlRequest request1 = new GetPreSignedUrlRequest
        {
            BucketName = bucket,
            Key = key,
            Expires = DateTime.Now.AddMinutes(5) //根据实际需要设置过期时间
        };
        string urlString = s3Client.GetPreSignedURL(request1);
        Console.WriteLine(urlString);
    }
    catch (AmazonS3Exception ex)
    {
        Console.WriteLine("Failed with HTTPStatus: {0}; \nErrorCode: {1}; \nErrorMessage: {2}; \nRequestID:{3};",
            ex.StatusCode, ex.ErrorCode, ex.Message, ex.RequestId);
    }
    catch (Exception ex)
    {
        Console.WriteLine("Failed with error info: {0}", ex.Message);
    }
}