我试图了解用于将文件上传到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所说,答案是肯定的,它将首先通过我的服务器,然后才能进入亚马逊。有点现在感觉像一个愚蠢的问题。
如果有人感兴趣,我决定使用带有Presigned URL的CORS AJAX上传到S3。起初相当复杂,但我现在有它工作。所以我的服务器可以高枕无忧,同时进行数以万计的上传!
答案 0 :(得分:2)
这一行:
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
在写入输出流之前,将字节读入服务器(不会保留在磁盘上,但保留在内存中)。因此,您的服务器不会被绕过。