简体   繁体   中英

Upload file to Amazon S3 with non default permission

I'm trying to upload a file to Amazon S3 using .NET SDK. The upload works fine, except it is applying the default permission to the uploaded file, which is 'Private'.

I'd like the permission on the uploaded files to be set to 'BucketOwnerFullControl'.

Below is my code, and I'm not quite sure what I need to do to it to get it working as such.

    static string accessKeyID = "";
    static string secretAccessKey = "";
    static string existingBucketName = "bucket";

    static void Main(string[] args)
    {
        NameValueCollection appConfig = ConfigurationManager.AppSettings;
        accessKeyID = appConfig["accesskey"];
        secretAccessKey = appConfig["secretkey"];

        string[] files = Directory.GetFiles("C:\\amazontestdirectory");

            foreach (string fileName in files)
            {
                try
                {
                    TransferUtility fileTransferUtility = new TransferUtility(accessKeyID, secretAccessKey);

                    // Upload a file, file name is used as the object key name.
                    fileTransferUtility.Upload(fileName, existingBucketName);
                }
                catch (AmazonS3Exception s3Exception)
                {
                    Console.WriteLine("AWS error: " + s3Exception.Message, s3Exception.InnerException);

                    //Open a file for writing
                    string errorOutputFileName = System.IO.Path.GetFullPath("C:\\amazontestdirectory\\logs\\errorLog.txt");

                    //Get a StreamWriter class that can be used to write to the file
                    if (File.Exists(errorOutputFileName))
                    {
                        StreamWriter objStreamWriter;
                        objStreamWriter = File.AppendText(errorOutputFileName);
                        objStreamWriter.WriteLine();
                        objStreamWriter.WriteLine(DateTime.Now.ToString() + " - AWS error: " + s3Exception.Message, s3Exception.InnerException);

                        //Close the stream
                        objStreamWriter.Close();
                    }
                }
            }
        }

To set the permissions while using the TransferUtility you need use the upload override that takes in a TransferUtilityUploadRequest. This lets you set the more advanced options when uploading a file.

TransferUtilityUploadRequest request = new TransferUtilityUploadRequest()
{
    BucketName = existingBucketName,
    FilePath = fileName,
    CannedACL = S3CannedACL.BucketOwnerFullControl
};

// Upload a file, file name is used as the object key name.
fileTransferUtility.Upload(request);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM