EKa*_*ily 40 .net c# amazon-s3
我厌倦了所有这些"上传到S3"的例子和教程不起作用,有人可以给我一个简单的例子并且非常容易吗?
EKa*_*ily 53
以下是您必须遵循的说明才能获得完整的演示程序...
1 - 下载并安装适用于.NET的Amazon Web服务SDK,您可以在(http://aws.amazon.com/sdk-for-net/)中找到它.因为我有visual studio 2010我选择安装3.5 .NET SDK.
2-开放视觉工作室并制作一个新项目,我有visual studio 2010,我正在使用一个控制台应用程序项目.
3-添加对AWSSDK.dll的引用,它与上面提到的Amazon Web服务SDK一起安装,在我的系统中,dll位于"C:\ Program Files(x86)\ AWS SDK for .NET\bin\Net35\AWSSDK" .DLL".
4-制作一个新的类文件,在这里称它为"AmazonUploader"类的完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;
namespace UploadToS3Demo
{
public class AmazonUploader
{
public bool sendMyFileToS3(string localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
{
// input explained :
// localFilePath = the full local file path e.g. "c:\mydir\mysubdir\myfilename.zip"
// bucketName : the name of the bucket in S3 ,the bucket should be alreadt created
// subDirectoryInBucket : if this string is not empty the file will be uploaded to
// a subdirectory with this name
// fileNameInS3 = the file name in the S3
// create an instance of IAmazonS3 class ,in my case i choose RegionEndpoint.EUWest1
// you can change that to APNortheast1 , APSoutheast1 , APSoutheast2 , CNNorth1
// SAEast1 , USEast1 , USGovCloudWest1 , USWest1 , USWest2 . this choice will not
// store your file in a different cloud storage but (i think) it differ in performance
// depending on your location
IAmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client(RegionEndpoint.EUWest1);
// create a TransferUtility instance passing it the IAmazonS3 created in the first step
TransferUtility utility = new TransferUtility(client);
// making a TransferUtilityUploadRequest instance
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
if (subDirectoryInBucket == "" || subDirectoryInBucket == null)
{
request.BucketName = bucketName; //no subdirectory just bucket name
}
else
{ // subdirectory and bucket name
request.BucketName = bucketName + @"/" + subDirectoryInBucket;
}
request.Key = fileNameInS3 ; //file name up in S3
request.FilePath = localFilePath; //local file name
utility.Upload(request); //commensing the transfer
return true; //indicate that the file was sent
}
}
}
Run Code Online (Sandbox Code Playgroud)
5-添加配置文件:在解决方案资源管理器中右键单击您的项目,然后选择"添加" - >"新项目",然后从列表中选择"应用程序配置文件"类型并单击"添加"按钮.一个名为"App.config"的文件被添加到解决方案中.
6-编辑app.config文件:双击解决方案资源管理器中的"app.config"文件,将出现编辑菜单.用以下文本替换所有文本:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="AWSProfileName" value="profile1"/>
<add key="AWSAccessKey" value="your Access Key goes here"/>
<add key="AWSSecretKey" value="your Secret Key goes here"/>
</appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)
您必须修改上述文本以反映您的Amazon Access Key Id和Secret Access Key.
7-现在在program.cs文件中(记住这是一个控制台应用程序)编写以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UploadToS3Demo
{
class Program
{
static void Main(string[] args)
{
// preparing our file and directory names
string fileToBackup = @"d:\mybackupFile.zip" ; // test file
string myBucketName = "mys3bucketname"; //your s3 bucket name goes here
string s3DirectoryName = "justdemodirectory";
string s3FileName = @"mybackupFile uploaded in 12-9-2014.zip";
AmazonUploader myUploader = new AmazonUploader();
myUploader.sendMyFileToS3(fileToBackup, myBucketName, s3DirectoryName, s3FileName);
}
}
}
Run Code Online (Sandbox Code Playgroud)
8-用您自己的数据替换上面代码中的字符串
9-添加错误纠正,您的程序就绪
mej*_*l57 43
@docesam的解决方案适用于旧版本的AWSSDK.以下是AmazonS3最新文档的示例:
1)首先打开Visual Studio(我正在使用VS2015)并创建一个新项目- > ASP.NET Web应用程序- > MVC.
2)浏览Manage Nuget Package,包AWSSDK.S3并安装它.
3)现在创建一个名为的类AmazonS3Uploader
,然后复制并粘贴这段代码:
using System;
using Amazon.S3;
using Amazon.S3.Model;
namespace AmazonS3Demo
{
public class AmazonS3Uploader
{
private string bucketName = "your-amazon-s3-bucket";
private string keyName = "the-name-of-your-file";
private string filePath = "C:\\Users\\yourUserName\\Desktop\\myImageToUpload.jpg";
public void UploadFile()
{
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
try
{
PutObjectRequest putRequest = new PutObjectRequest
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
ContentType = "text/plain"
};
PutObjectResponse response = client.PutObject(putRequest);
}
catch (AmazonS3Exception amazonS3Exception)
{
if (amazonS3Exception.ErrorCode != null &&
(amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
||
amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
{
throw new Exception("Check the provided AWS Credentials.");
}
else
{
throw new Exception("Error occurred: " + amazonS3Exception.Message);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
4)编辑你的Web.config文件,添加下面的行<appSettings></appSettings>
:
<add key="AWSProfileName" value="any name for your profile"/>
<add key="AWSAccessKey" value="your Access Key goes here"/>
<add key="AWSSecretKey" value="your Secret Key goes here"/>
Run Code Online (Sandbox Code Playgroud)
5)现在UploadFile
从HomeController.cs调用你的方法来测试它:
public class HomeController : Controller
{
public ActionResult Index()
{
AmazonS3Uploader amazonS3 = new AmazonS3Uploader();
amazonS3.UploadFile();
return View();
}
....
Run Code Online (Sandbox Code Playgroud)
6)在您的Amazon S3存储桶中找到您的文件,这就是全部.
Hoo*_*ini 11
我已经写了一个关于这个的教程。
使用低级 API 将文件上传到 S3 存储桶:
IAmazonS3 client = new AmazonS3Client("AKI...access-key...", "+8Bo...secrey-key...", RegionEndpoint.APSoutheast2);
FileInfo file = new FileInfo(@"c:\test.txt");
string destPath = "folder/sub-folder/test.txt"; // <-- low-level s3 path uses /
PutObjectRequest request = new PutObjectRequest()
{
InputStream = file.OpenRead(),
BucketName = "my-bucket-name",
Key = destPath // <-- in S3 key represents a path
};
PutObjectResponse response = client.PutObject(request);
Run Code Online (Sandbox Code Playgroud)
使用高级 API 将文件上传到 S3 存储桶:
IAmazonS3 client = new AmazonS3Client("AKI...access-key...", "+8Bo...secrey-key...", RegionEndpoint.APSoutheast2);
FileInfo localFile = new FileInfo(@"c:\test.txt");
string destPath = @"folder\sub-folder\test.txt"; // <-- high-level s3 path uses \
S3FileInfo s3File = new S3FileInfo(client, "my-bucket-name", destPath);
if (!s3File.Exists)
{
using (var s3Stream = s3File.Create()) // <-- create file in S3
{
localFile.OpenRead().CopyTo(s3Stream); // <-- copy the content to S3
}
}
Run Code Online (Sandbox Code Playgroud)
@mejiamanuel57 的解决方案适用于 15MB 以下的小文件。对于较大的文件,我得到了System.Net.Sockets.SocketException: The I/O operation has been aborted because of either a thread exit or an application request
. 以下改进的解决方案适用于较大的文件(使用 50MB 文件进行测试):
...
public void UploadFile()
{
var client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
var transferUtility = new TransferUtility(client);
try
{
TransferUtilityUploadRequest transferUtilityUploadRequest = new TransferUtilityUploadRequest
{
BucketName = bucketName,
Key = keyName,
FilePath = filePath,
ContentType = "text/plain"
};
transferUtility.Upload(transferUtilityUploadRequest); // use UploadAsync if possible
}
...
Run Code Online (Sandbox Code Playgroud)
更多信息请点击这里。
归档时间: |
|
查看次数: |
55956 次 |
最近记录: |