我在上传文件以保存到S3时遇到了一些麻烦。我的第一次尝试是:
Result SaveFile(System.Web.HttpPostedFileBase file, string path)
{
//Keys are in web.config
var t = new Amazon.S3.Transfer.TransferUtility(Amazon.RegionEndpoint.USWest2);
try
{
t.Upload(new Amazon.S3.Transfer.TransferUtilityUploadRequest
{
BucketName = Bucket,
InputStream = file.InputStream,
Key = path
});
}
catch (Exception ex)
{
return Result.FailResult(ex.Message);
}
return Result.SuccessResult();
}
这会抛出异常,并显示以下消息:“我们计算的请求签名与您提供的签名不匹配。请检查您的密钥和签名方法。”我也尝试将file.InputStream复制到MemoryStream,然后上传,同样的错误 如果我将InputStream设置为:
new FileStream(@"c:\folder\file.txt", FileMode.Open)
然后文件上传很好。在上传文件之前,我真的需要将文件保存到磁盘吗?
答案 0 :(得分:1)
这是我的工作版首先上传方法:
public bool Upload(string filePath, Stream inputStream, double contentLength, string contentType)
{
try
{
var request = new PutObjectRequest();
request.WithBucketName(_bucketName)
.WithCannedACL(S3CannedACL.PublicRead)
.WithKey(filePath).InputStream = inputStream;
request.AddHeaders(AmazonS3Util.CreateHeaderEntry("ContentType", contentType));
_amazonS3Client.PutObject(request);
}
catch (Exception exception)
{
// log or throw;
return false;
}
return true;
}
我刚收到HttpPostedFileBase.InputStream
(注意,这是旧版本的Api,不再支持WithBucketName
语法,只是直接设置属性)
答案 1 :(得分:0)
在shenku的评论之后,对于较新版本的SDK。
public bool Upload(string filePath, Stream inputStream, double contentLength, string contentType)
{
try
{
var request = new PutObjectRequest();
string _bucketName = "";
request.BucketName = _bucketName;
request.CannedACL = S3CannedACL.PublicRead;
request.InputStream = inputStream;
request.Key = filePath;
request.Headers.ContentType = contentType;
PutObjectResponse response = _amazonS3Client.PutObject(request);
return true;
}catch(Exception ex)
{
return false;
}
}