如何将内存文件上传到亚马逊S3?

Ben*_* Ae 5 c# amazon-s3 amazon-web-services

我想从memoryStream上传文件到亚马逊S3服务器.

这是代码:

public static bool memUploadFile(AmazonS3 client, MemoryStream memFile, string toPath)
{

    try
    {
        Amazon.S3.Transfer.TransferUtility tranUtility = new Amazon.S3.Transfer.TransferUtility(client);
        tranUtility.Upload(filePath, toPath.Replace("\\", "/"));

        return true;
    }
    catch (Exception ex)
    {
        return false;
    }

}
Run Code Online (Sandbox Code Playgroud)

然后错误说,

"'Amazon.S3.Transfer.TransferUtility.Uplaod(string,string)'的最佳重载方法匹配'有一些无效的参数"

Ham*_*yan 7

查看上传方法(stream,bucketName,key)

public static bool memUploadFile(AmazonS3 client, MemoryStream memFile, string toPath)
{
    try
    {
        using(Amazon.S3.Transfer.TransferUtility tranUtility =
                      new Amazon.S3.Transfer.TransferUtility(client))
        {
            tranUtility.Upload(memFile, toPath.Replace("\\", "/"), <The key under which the Amazon S3 object is stored.>);

            return true;
        }
    }
    catch (Exception ex)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)


Fai*_*oor 5

哈姆雷特是对的。这是一个示例 TransferUtilityUploadRequest

    [Test]
    public void UploadMemoryFile()
    {
        var config = CloudConfigStorage.GetAdminConfig();

        string bucketName = config.BucketName;
        string clientAccessKey = config.ClientAccessKey;
        string clientSecretKey = config.ClientSecretKey;

        string path = Path.GetFullPath(@"dummy.txt");
        File.WriteAllText(path, DateTime.Now.ToLongTimeString());

        using (var client = AWSClientFactory.CreateAmazonS3Client(clientAccessKey, clientSecretKey))
        using (var transferUtility = new TransferUtility(client))
        {

            var request = new TransferUtilityUploadRequest
            {
                BucketName = bucketName,
                Key = "memory.txt",
                InputStream = new MemoryStream(File.ReadAllBytes(path))
            };

            transferUtility.Upload(request);
        }
    }   
Run Code Online (Sandbox Code Playgroud)