aws s3 使用webapi上传文件
前言:最近使用紫光云的OSS存储图片,他们使用aws s3存储的图片,给我的文档很难读懂.网上翻阅资料,实现webapi上传文件
1.下载Amazon提供的sdk
2.实现代码
using Amazon.S3; using Amazon.S3.Model; using System; using System.Web; namespace OSS{ public class OSSUploadTest { /// <summary> /// 桶名称 /// </summary> private const string bucketName = "****"; private static string accessKey = System.Configuration.ConfigurationManager.AppSettings["AWSAccessKey"]; private static string secretKey = System.Configuration.ConfigurationManager.AppSettings["AWSSecretKey"]; /// <summary> /// 文件上传 /// </summary> /// <param name="file">文件</param> /// <param name="folder">文件夹</param> /// <returns></returns> public bool UploadFile(HttpPostedFileBase file, string folder) { try { var config = new AmazonS3Config() { ServiceURL = "http://***.unicloudsrv.com/" }; using (AmazonS3Client client = new AmazonS3Client( accessKey, secretKey, config )) { var stream = file.InputStream; string name = folder + "/" + file.FileName; var putObjectRequest = new PutObjectRequest { BucketName = bucketName, Timeout = TimeSpan.FromSeconds(5), InputStream = stream, Key = name, CannedACL = S3CannedACL.PublicRead, StorageClass = S3StorageClass.Standard, ServerSideEncryptionMethod = ServerSideEncryptionMethod.None, }; var data = client.PutObject(putObjectRequest); if (data.HttpStatusCode == System.Net.HttpStatusCode.OK) { return true; } return false; } } catch (Exception exception) { Console.WriteLine(exception); return false; } } } }
其中:
bucketName 是桶名称
ServiceURL 是Endpoint
accessKey 是 AccessKey ID
secretKey 是 AccessKey Secret
AccessKey ID和AccessKey Secret是您访问紫光云API的密钥,在控制台查看(配置在web.config中)
3.控制器
/// <summary> /// 上传图片 /// </summary> /// <returns></returns> [HttpPost] [Route("v3/uploads")] public IHttpActionResult Uploads() { var id = "123"; HttpPostedFile file = HttpContext.Current.Request.Files["file"]; if (string.IsNullOrEmpty(id)) { return Json(false); } string type = "receipt"; var folder = $"{type}/{id}"; var data = new OSSUploadTest().UploadFile(new HttpPostedFileWrapper(file) as HttpPostedFileBase, folder); return Json(data);