//图片上传到阿里云 [AcceptVerbs(HttpVerbs.Post)] public JsonResult Upload(HttpPostedFileBase fileData, string tupianming) { if (fileData != null) { try { // 文件上传后的保存路径 var extName = Path.GetExtension(fileData.FileName); if (string.IsNullOrWhiteSpace(extName)) { return Json(new { Success = false, Message = "extName is null!" }); } var extNameToLower = extName.ToLower(); var accessId = System.Configuration.ConfigurationManager.AppSettings["ossKeyId"]; var accessKey = System.Configuration.ConfigurationManager.AppSettings["ossKeySectet"]; var bucketName = "xiaoyaodijun"; //System.Configuration.ConfigurationManager.AppSettings["bucketName"]; var endpoint = "http://oss-cn-qingdao.aliyuncs.com "; var extenname = ".oss-cn-qingdao.aliyuncs.com/"; //图片的存储路径和名字 var fileName = "xiaoyao/124" + extNameToLower; OssClient client = new OssClient(endpoint, accessId, accessKey); System.IO.Stream inputStream = fileData.InputStream; ObjectMetadata objectMetadata = new ObjectMetadata(); client.PutObject(bucketName, fileName, inputStream, objectMetadata); //返回图片路径 AccessControlList bucketAcl = client.GetBucketAcl(bucketName); var result = ((!bucketAcl.Grants.Any()) ? client.GeneratePresignedUri(bucketName, fileName, System.DateTime.Now.AddMinutes(5.0)).AbsoluteUri : string.Format("http://{0}{1}{2}", bucketName, extenname, fileName)); inputStream.Dispose(); } catch (Exception ex) { return Json(new { Success = false, Message = ex.Message }); } } else { return Json(new { Success = false, Message = "请选择要上传的文件!" }); } return null; }
第二
Step 1. 初始化一个OSSClient OSSClient是与OSS服务交互的客户端,SDK的OSS操作都是通过OSSClient完成的。 下面代码新建了一个OSSClient: using Aliyun.OpenServices.OpenStorageService; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AliyunTest { class Program { static readonly string accessKeyId = "AccessKeyId"; static readonly string accessKeySecret = "AccessKeySecret"; //关于这个endPoint,可以参考:http://bbs.aliyun.com/read/149100.html?spm=5176.7189909.0.0.YiwiFw static readonly string endPoint = "http://oss-cn-beijing.aliyuncs.com"; static void Main(string[] args) { //初始化 OSSClient OssClient ossClient = new OssClient(endPoint, accessKeyId, accessKeySecret); //使用代码... } } }
Step 2. 新建Bucket Bucket是OSS上的命名空间,相当于数据的容器,可以存储若干数据实体(Object)。 你可以按照下面的代码新建一个Bucket: /// <summary> /// 新建存储对象容器Bucket /// </summary> /// <param name="bucketName">容器名称</param> void CreateBucket(string bucketName) { //初始化 OSSClient OssClient ossClient = new OssClient(endPoint, accessKeyId, accessKeySecret); // 新建一个Bucket var bucket = ossClient.CreateBucket(bucketName); Console.WriteLine(bucket.CreationDate); } 复制代码
/// <summary> /// 进行对象存储 /// </summary> /// <param name="bucketName">bucket名称</param> void PutObject(string bucketName) { //初始化 OSSClient OssClient ossClient = new OssClient(endPoint, accessKeyId, accessKeySecret); //定义文件流 var objStream = new System.IO.FileStream("D:\example\test.jpg", System.IO.FileMode.OpenOrCreate); //定义 object 描述 var objMetadata = new ObjectMetadata(); var objKey = "test.jpg"; //执行 put 请求,并且返回对象的MD5摘要。 var putResult = ossClient.PutObject(bucketName, objKey, objStream, objMetadata); Console.WriteLine(putResult.ETag); }
Object通过InputStream的形式上传到OSS中。在上面的例子里我们可以看出,每上传一个Object,都需要指定和Object关 联的ObjectMetadata。ObjectMetaData是用户对该object的描述,由一系列name-value对组成;其中 ContentLength是必须设置的,以便SDK可以正确识别上传Object的大小。
Put Object请求处理成功后,OSS会将收到文件的MD5值放在返回结果的ETag中。用户可以根据ETag检验上传的文件与本地的是否一致。
/// <summary> /// 获取一个存储对象 /// </summary> /// <param name="bucketName">bucket名称</param> /// <param name="objKey">对象标识名称</param> void GetObject(string bucketName, string objKey) { //初始化 OSSClient OssClient ossClient = new OssClient(endPoint, accessKeyId, accessKeySecret); //获取对象 var obj = ossClient.GetObject(bucketName, objKey); //获取Object的输入流 var objStream = obj.Content; //怎么处理数据流,您看着办吧。 //... //最后关闭数据流。 objStream.Close(); }
文章来源:http://www.cnblogs.com/easeyeah/p/4109584.html
三:大文件分块上传
//切块上传大文件到阿里云 private void button4_Click(object sender, EventArgs e) { OpenFileDialog dia = new OpenFileDialog(); dia.ShowDialog(); var filePath = dia.FileName; var name = dia.SafeFileName; UploadBigFile(filePath, name); } public void UploadBigFile(string filepath, string name) { var accessId = "mqPwT*****Jw1paW"; var accessKey = "GM63rs2adiXu******69nSm"; var bucketName = "xiao***un"; //oss所在的地区 var endpoint = "http://oss-cn-qingdao.aliyuncs.com "; var extenname = ".oss-cn-qingdao.aliyuncs.com/"; //后缀 var extName = Path.GetExtension(filepath); var fileName = "xiaoyaofile/" + name; OssClient client = new OssClient(endpoint, accessId, accessKey); InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(bucketName, fileName); InitiateMultipartUploadResult initiateMultipartUploadResult = client.InitiateMultipartUpload(initiateMultipartUploadRequest); int partSize = 1024 * 1024 * 1; FileInfo fi = new FileInfo(filepath); int partCount = (int)(fi.Length / partSize); if (fi.Length % partSize != 0) { partCount++; } List<PartETag> partETags = new List<PartETag>(); for (int i = 0; i < partCount; i++) { FileStream fis = File.Open(filepath, FileMode.Open); long skipbytes = partSize * i; fis.Seek(skipbytes, SeekOrigin.Begin); long size = partSize < fi.Length - skipbytes ? partSize : fi.Length - skipbytes; UploadPartRequest uploadPartRequest = new UploadPartRequest(bucketName, fileName, initiateMultipartUploadResult.UploadId); uploadPartRequest.InputStream = fis; uploadPartRequest.PartSize = partSize; uploadPartRequest.PartNumber = i + 1; UploadPartResult uploadPartResult = client.UploadPart(uploadPartRequest); partETags.Add(uploadPartResult.PartETag); fis.Close(); var k = (Convert.ToDouble(i)) / partCount; textBox2.Text = (k * 100).ToString(); } CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, fileName, initiateMultipartUploadResult.UploadId); if (completeMultipartUploadRequest.PartETags != null) { for (int i = 0; i < partETags.Count; i++) { completeMultipartUploadRequest.PartETags.Add(partETags[i]); } } CompleteMultipartUploadResult completeMultipartUploadResult = client.CompleteMultipartUpload(completeMultipartUploadRequest); }