Recently, the project needs to use the AWS S3 API to implement file upload and download function, only to find that the internet about. NET implementation of this feature is not many articles, there are a few are also very old version of the use of AWS description, writing and packaging classes, etc. are basically scrapped. Although this, but still very grateful that several articles gave me direction. I'll give you a way to implement the API:
Note: This API implementation method is implemented based on the awssdk.2.3.50.1 version .
1. First, you must have an Amazon Web services account to access this service, there is currently a certain amount of traffic, when traffic exceeds the charge automatically
2. Depending on the access key provided (access keys) and secret key (secret key) and Bucketname
private static readonly string _awsaccesskey = "Your Access Key"; private static readonly string _awssecretkey = "Your Secret Key"; private static readonly string _bucketname = "Your Bucket Name";
3. Provide the most basic one configuration, this address is fixed
Amazons3config config = new Amazons3config () { serviceurl = "http://s3.amazonaws.com" };
4. Normal Upload method (based on MVC framework):
<summary>//upload///</summary>// <param name= "file" ></param> public void Upload (httppostedfilebase file) { using (client = new Amazons3client (_awsaccesskey, _awssecretkey, config ) { var request = new Putobjectrequest () { bucketname = _bucketname, cannedacl = S3cannedacl.publicread, Key = string. Format ("uploads/{0}", file. FileName), inputstream = file. InputStream }; Client. PutObject (request); } }
where Cannedacl = S3cannedacl.publicread Set the upload file permissions, you can read the key is the file name after the upload or a unique indicator, here file. FileName is a path, and you can modify it yourself to the name you want to save.
The other two don't have to explain. Haha, after testing, smooth through, good happy ~ ~ No white Research
5. Here's how to download:
public void Download () { using (client = new Amazons3client (_awsaccesskey, _awssecretkey, config)) { Getobjectrequest request = new Getobjectrequest () { bucketname = _bucketname, Key = "Test" }; Getobjectresponse response = client. GetObject (request); Response. Writeresponsestreamtofile ("C:\\users\\documents\\backtitle.png"); } }
Download method is simple, needless to say, tested through, haha ~ ~ Happy
Today to provide these ha, but also need to study the multi-threaded upload, another day to provide multi-threaded uploads and other methods.
If there is a problem, please leave a message, if there is a wrong place, also ask the warrior.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
AWS S3 API implementation file upload download