【发布时间】:2014-08-10 13:39:03
【问题描述】:
我试图了解用于将文件上传到 S3 的特定 .NET SDK 示例 (seen here) 是先上传到我的服务器,还是直接上传到 S3?
我怀疑文件首先上传到我的服务器,然后保存到 S3。但也许 SDK 会神奇地绕过我的服务器?代码如下:
using System;
using System.IO;
using System.Net;
using Amazon.S3;
using Amazon.S3.Model;
namespace s3.amazon.com.docsamples
{
class UploadObjcetUsingPresignedURL
{
static IAmazonS3 s3Client;
// File to upload.
static string filePath = "*** Specify file to upload ***";
// Information to generate pre-signed object URL.
static string bucketName = "*** Provide bucket name ***";
static string objectKey = "*** Provide object key for the new object ***";
public static void Main(string[] args)
{
try
{
using (s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1))
{
string url = GeneratePreSignedURL();
UploadObject(url);
}
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
Console.WriteLine("Check the provided AWS Credentials.");
Console.WriteLine(
"To sign up for service, go to http://aws.amazon.com/s3");
}
else
{
Console.WriteLine(
"Error occurred. Message:'{0}' when listing objects",
amazonS3Exception.Message);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
static void UploadObject(string url)
{
HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
httpRequest.Method = "PUT";
using (Stream dataStream = httpRequest.GetRequestStream())
{
byte[] buffer = new byte[8000];
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
dataStream.Write(buffer, 0, bytesRead);
}
}
}
HttpWebResponse response = httpRequest.GetResponse() as HttpWebResponse;
}
static string GeneratePreSignedURL()
{
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest
{
BucketName = bucketName,
Key = objectKey,
Verb = HttpVerb.PUT,
Expires = DateTime.Now.AddMinutes(5)
};
string url = null;
url = s3Client.GetPreSignedURL(request);
return url;
}
}
}
问题又来了
上面的例子是不是先上传到服务器,再传文件到S3?还是以某种方式绕过服务器并直接上传到 S3?
谢谢!
编辑
正如 TJ 所说,答案是肯定的,它会在到达亚马逊之前先通过我的服务器。现在感觉有点像一个愚蠢的问题。
如果有人感兴趣,我决定使用带有预签名 URL 的 CORS AJAX 上传到 S3。起初相当复杂,但我现在可以正常工作了。因此,我的服务器可以高枕无忧,同时进行无数次上传!
【问题讨论】:
标签: c# .net amazon-web-services sdk