【发布时间】:2017-10-06 18:21:05
【问题描述】:
我正在尝试从 amazon s3 下载文件。我为此使用.NET sdk。我已经写下了以下代码:
GetObjectRequest request = new GetObjectRequest()
.WithKey("abc/xyz.jpg")
.WithBucketName(appConfig);
using (GetObjectResponse response = s3Client.GetObject(request))
{
int numBytesToRead = (int)response.ContentLength;
if (numBytesToRead > 0)
{
int numBytesRead = 0;
byte[] buffer = new byte32768;
using (FileStream fstream = new FileStream(@"C:\abc\xyz.jpg", FileMode.Create))
{
using (Stream responseStream = response.ResponseStream)
{
do
{
numBytesRead = responseStream.Read(buffer, 0, buffer.Length);
fstream.Write(buffer, 0, numBytesRead);
}
while (numBytesRead > 0);
}
}
}
}
使用此代码,我可以下载文件。但现在我想下载多个文件。为此,我首先列出 s3 上可用的所有文件,然后将其存储在 arraylist 中,然后为每个文件调用我的下载函数。
在我使用 (GetObjectResponse response = s3Client.GetObject(request)) 后调用下载函数时运行列表文件方法后出现异常。
{“拒绝访问”}
Stack trace:
at Amazon.S3.AmazonS3Client.processRequestError(String actionName, HttpWebRequest request, WebException we, HttpWebResponse errorResponse, String requestAddr, WebHeaderCollection& respHdrs, Type t, Exception& cause)
at Amazon.S3.AmazonS3Client.handleHttpWebErrorResponse(S3Request userRequest, WebException we, HttpWebRequest request, HttpWebResponse httpResponse, Exception& cause, HttpStatusCode& statusCode)
at Amazon.S3.AmazonS3Client.getResponseCallback[T](IAsyncResult result)
at Amazon.S3.AmazonS3Client.endOperation[T](IAsyncResult result)
at Amazon.S3.AmazonS3Client.EndGetObject(IAsyncResult asyncResult)
at Amazon.S3.AmazonS3Client.GetObject(GetObjectRequest request)
at ScreenshotsUploader.ScreenshotsUploader.downloadFile(AmazonS3 s3Client, NameValueCollection appConfig) in c:\Users\xyz\Documents\Visual Studio 2012\Projects\ScreenshotsUploader\ScreenshotsUploader\ScreenshotsUploader.cs:line 220
at ScreenshotsUploader.ScreenshotsUploader.GetServiceOutput() in c:\Users\xyz\Documents\Visual Studio 2012\Projects\ScreenshotsUploader\ScreenshotsUploader\ScreenshotsUploader.cs:line 55
状态码:
System.Net.HttpStatusCode.Forbidden
我需要做什么来解决这个问题?
我也尝试了不同的方法来下载文件并得到同样的错误:
第二种方法:
string fileToDownload = @"xyzjpg";
string saveToo = @"C:\xyz.jpg";
TransferUtilityDownloadRequest request = new TransferUtilityDownloadRequest().WithBucketName(appConfig).WithKey(fileToDownload).WithFilePath(saveToo);
TransferUtility tu = new TransferUtility(s3Client);
tu.Download(request);
提前致谢。
【问题讨论】:
-
您可以包含您的存储桶策略吗?您的 IAM 对存储桶有哪些权限?
-
这看起来可能是权限问题。如果没有,您可以发布您的实际代码吗?我只看到文件名、对象键等的字符串文字。
-
我没有更改(添加/编辑)权限和策略中的任何内容。我刚刚创建了存储桶并将文件上传到存储桶。
-
在这两种方法中我都可以下载文件(单个文件)。有没有其他方法可以下载所有文件?
-
您在实例化 S3Client 时指定您的 aws 凭证。可能是重用该对象造成了这个问题。您能否尝试看看如果在每次迭代中(遍历数组列表时)您创建一个新的 S3Client 并将其传递给您的单个文件下载函数会发生什么。
标签: c# .net amazon-web-services amazon-s3