在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → 阿里云 OSS上传下载文件 实例源码下载

阿里云 OSS上传下载文件 实例源码下载

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:0.40M
  • 下载次数:61
  • 浏览次数:1080
  • 发布时间:2017-05-22
  • 实例类别:C#语言基础
  • 发 布 人:crazycode
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 上传 阿里云 文件 下载 OSS

实例介绍

【实例简介】
【实例截图】

【核心代码】

using System;
using System.IO;
using System.Net;
using System.Text;
using Aliyun.OSS;
using Aliyun.OSS.Test.Util;

using NUnit.Framework;

namespace Aliyun.OSS.Test.TestClass.ObjectTestClass
{
    [TestFixture]
    public class ObjectSignedUriTest
    {
        private static IOss _ossClient;
        private static string _className;
        private static string _bucketName;
        private static string _objectKey;
        private static string _objectETag;

        [TestFixtureSetUp]
        public static void ClassInitialize()
        {
            //get a OSS client object
            _ossClient = OssClientFactory.CreateOssClient();
            //get current class name, which is prefix of bucket/object
            _className = TestContext.CurrentContext.Test.FullName;
            _className = _className.Substring(_className.LastIndexOf('.')   1).ToLowerInvariant();
            //create the bucket
            _bucketName = OssTestUtils.GetBucketName(_className);
            _ossClient.CreateBucket(_bucketName);
            //create sample object
            _objectKey = OssTestUtils.GetObjectKey(_className);
            var poResult = OssTestUtils.UploadObject(_ossClient, _bucketName, _objectKey,
                Config.UploadTestFile, new ObjectMetadata());
            _objectETag = poResult.ETag;
        }

        [TestFixtureTearDown]
        public static void ClassCleanup()
        {
            OssTestUtils.CleanBucket(_ossClient, _bucketName);
        }

        #region GET methods
        [Test]
        public void GetPreSignedUriDefaultPositiveTest()
        {
            HttpWebRequest req = null;
            HttpWebResponse res = null;

            var now = DateTime.Now;
            //set expiration time to 5 seconds later
            var expireDate = now.AddSeconds(5);
            var uri = _ossClient.GeneratePresignedUri(_bucketName, _objectKey, expireDate);
            try
            {
                req = WebRequest.Create(uri) as HttpWebRequest;
                req.Method = "GET";
                res = req.GetResponse() as HttpWebResponse;
                Assert.AreEqual(HttpStatusCode.OK, res.StatusCode, "response status code is not expected.");
                using (var stream = res.GetResponseStream())
                {
                    var actualETag = FileUtils.ComputeContentMd5(stream);
                    Assert.AreEqual(_objectETag.ToLowerInvariant(), actualETag.ToLowerInvariant());
                }
            }
            catch (WebException)
            {
                //TODO:
            }
            finally
            {
                if(req != null) req.Abort();
                if(res != null) res.Close();
            }
        }

        [Test]
        public void GetPreSignedUriDefaultNegativeTest()
        {
            HttpWebRequest req = null;
            HttpWebResponse res = null;

            var now = DateTime.Now;
            //set expiration time to 5 seconds before
            var expireDate = now.AddSeconds(-5);
            var uri = _ossClient.GeneratePresignedUri(_bucketName, _objectKey, expireDate);
            try
            {
                req = WebRequest.Create(uri) as HttpWebRequest;
                req.Method = "GET";
                res = req.GetResponse() as HttpWebResponse;
                Assert.Fail("response fail for expired URI");
            }
            catch (WebException e)
            {
                Assert.IsTrue(e.Message.Contains("403"), 
                    string.Format("Unexpected exception: {0}", e.Message));
            }
            finally
            {
                if (req != null) req.Abort();
                if (res != null) res.Close();
            }
        }

        [Test]
        public void GetPreSignedUriWithContentTypeAndMd5PositiveTest()
        {
            HttpWebRequest req = null;
            HttpWebResponse res = null;

            var now = DateTime.Now;
            //set expiration time to 5 seconds later
            var expireDate = now.AddSeconds(5);
            var gpuRequest = new GeneratePresignedUriRequest(_bucketName, _objectKey);
            gpuRequest.Expiration = expireDate;
            gpuRequest.ContentType = "application/zip";
            gpuRequest.ContentMd5 = _objectETag;
            var uri = _ossClient.GeneratePresignedUri(gpuRequest);

            try
            {
                req = WebRequest.Create(uri) as HttpWebRequest;
                req.Method = "GET";
                req.ContentType = "application/zip";
                req.Headers.Add(HttpRequestHeader.ContentMd5, _objectETag);
                res = req.GetResponse() as HttpWebResponse;
                Assert.AreEqual(HttpStatusCode.OK, res.StatusCode, "response status code is not expected.");
                using (var stream = res.GetResponseStream())
                {
                    var actualETag = FileUtils.ComputeContentMd5(stream);
                    Assert.AreEqual(_objectETag.ToLowerInvariant(), actualETag.ToLowerInvariant());
                }
            }
            catch (WebException)
            {
                //TODO:
            }
            finally
            {
                if (req != null) req.Abort();
                if (res != null) res.Close();
            }
        }

        [Test]
        public void GetPreSignedUriWithContentTypeAndMd5NegativeTest()
        {
            HttpWebRequest req = null;
            HttpWebResponse res = null;

            var now = DateTime.Now;
            //set expiration time to 5 seconds later
            var expireDate = now.AddSeconds(5);
            var gpuRequest = new GeneratePresignedUriRequest(_bucketName, _objectKey);
            gpuRequest.Expiration = expireDate;
            //do not set content type
            //gpuRequest.ContentType = "application/zip";
            gpuRequest.ContentMd5 = _objectETag;
            var uri = _ossClient.GeneratePresignedUri(gpuRequest);

            try
            {
                req = WebRequest.Create(uri) as HttpWebRequest;
                req.Method = "GET";
                req.ContentType = "application/zip";
                req.Headers.Add(HttpRequestHeader.ContentMd5, _objectETag);
                res = req.GetResponse() as HttpWebResponse;
                Assert.Fail("response fail for expired URI");
            }
            catch (WebException e)
            {
                Assert.IsTrue(e.Message.Contains("403"),
                    string.Format("Unexpected exception: {0}", e.Message));
            }
            finally
            {
                if (req != null) req.Abort();
                if (res != null) res.Close();
            }
        }

        [Test]
        public void GetPreSignedUriWithUserMetaPositiveTest()
        {
            HttpWebRequest req = null;
            HttpWebResponse res = null;

            var now = DateTime.Now;
            //set expiration time to 5 seconds later
            var expireDate = now.AddSeconds(5);
            var gpuRequest = new GeneratePresignedUriRequest(_bucketName, _objectKey);
            gpuRequest.Expiration = expireDate;
            gpuRequest.UserMetadata.Add("name1", "vaue1");
            gpuRequest.UserMetadata.Add("name2", "vaue2");
            var uri = _ossClient.GeneratePresignedUri(gpuRequest);

            try
            {
                req = WebRequest.Create(uri) as HttpWebRequest;
                req.Method = "GET";
                req.Headers.Add("x-oss-meta-name1", "vaue1");
                req.Headers.Add("x-oss-meta-name2", "vaue2");
                res = req.GetResponse() as HttpWebResponse;
                Assert.AreEqual(HttpStatusCode.OK, res.StatusCode, "response status code is not expected.");
                using (var stream = res.GetResponseStream())
                {
                    var actualETag = FileUtils.ComputeContentMd5(stream);
                    Assert.AreEqual(_objectETag.ToLowerInvariant(), actualETag.ToLowerInvariant());
                }
            }
            catch (WebException)
            {
                //TODO:
            }
            finally
            {
                if (req != null) req.Abort();
                if (res != null) res.Close();
            }
        }

        [Test]
        public void GetPreSignedUriWithResponseHeaderPositiveTest()
        {
            HttpWebRequest req = null;
            HttpWebResponse res = null;

            var now = DateTime.Now;
            //set expiration time to 5 seconds later
            var expireDate = now.AddSeconds(5);
            var gpuRequest = new GeneratePresignedUriRequest(_bucketName, _objectKey)
            {
                Expiration = expireDate,
                ResponseHeaders =
                {
                    CacheControl = "No-cache",
                    ContentType = "application/zip",
                    ContentDisposition = "myDownload.zip"
                }
            };
            var uri = _ossClient.GeneratePresignedUri(gpuRequest);

            try
            {
                req = WebRequest.Create(uri) as HttpWebRequest;
                req.Method = "GET";
                res = req.GetResponse() as HttpWebResponse;
                Assert.AreEqual(HttpStatusCode.OK, res.StatusCode, "response status code is not expected.");
                using (var stream = res.GetResponseStream())
                {
                    var actualETag = FileUtils.ComputeContentMd5(stream);
                    Assert.AreEqual(_objectETag.ToLowerInvariant(), actualETag.ToLowerInvariant());
                }
            }
            catch (WebException)
            {
                //TODO:
            }
            finally
            {
                if (req != null) req.Abort();
                if (res != null) res.Close();
            }
        }

        [Test]
        public void GetPreSignedUriFullSettingsPositiveTest()
        {
            HttpWebRequest req = null;
            HttpWebResponse res = null;

            var now = DateTime.Now;
            //set expiration time to 5 seconds later
            var expireDate = now.AddSeconds(5);
            var gpuRequest = new GeneratePresignedUriRequest(_bucketName, _objectKey)
            {
                Expiration = expireDate,
                ContentType = "application/zip",
                ContentMd5 = _objectETag,
                ResponseHeaders =
                {
                    CacheControl = "No-cache",
                    ContentType = "application/zip",
                    ContentDisposition = "myDownload.zip"
                }
            };

            gpuRequest.AddUserMetadata("name1", "vaue1");
            gpuRequest.AddUserMetadata("name2", "vaue2");
            var uri = _ossClient.GeneratePresignedUri(gpuRequest);

            try
            {
                req = WebRequest.Create(uri) as HttpWebRequest;
                req.Method = "GET";

                req.ContentType = "application/zip";
                req.Headers.Add(HttpRequestHeader.ContentMd5, _objectETag);

                req.Headers.Add("x-oss-meta-name1", "vaue1");
                req.Headers.Add("x-oss-meta-name2", "vaue2");
                res = req.GetResponse() as HttpWebResponse;
                Assert.AreEqual(HttpStatusCode.OK, res.StatusCode, "response status code is not expected.");
                using (var stream = res.GetResponseStream())
                {
                    var actualETag = FileUtils.ComputeContentMd5(stream);
                    Assert.AreEqual(_objectETag.ToLowerInvariant(), actualETag.ToLowerInvariant());
                }
            }
            catch (WebException)
            {
                //TODO:
            }
            finally
            {
                if (req != null) req.Abort();
                if (res != null) res.Close();
            }
        }
        #endregion

        #region PUT methods
        [Test]
        public void PutPreSignedUriDefaultPositiveTest()
        {
            var testStr = FileUtils.GenerateOneKb();
            var bytes = Encoding.ASCII.GetBytes(testStr);
            //calculate the expected ETag
            var expectedETag = FileUtils.ComputeContentMd5(new MemoryStream(bytes));

            HttpWebRequest req = null;
            HttpWebResponse res = null;

            var now = DateTime.Now;
            //set expiration time to 5 seconds later
            var expireDate = now.AddSeconds(5);
            var targetObject = OssTestUtils.GetObjectKey(_className);
            var uri = _ossClient.GeneratePresignedUri(_bucketName, targetObject, expireDate, SignHttpMethod.Put);
            try
            {
                req = WebRequest.Create(uri) as HttpWebRequest;
                req.Method = "PUT";
                using (var stream = req.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
                try
                {
                    res = req.GetResponse() as HttpWebResponse;
                    Assert.AreEqual(HttpStatusCode.OK, res.StatusCode, "response status code is not expected.");
                    //get the uploaded object ETag
                    var actualETag = _ossClient.GetObjectMetadata(_bucketName, targetObject).ETag;
                    Assert.AreEqual(expectedETag.ToLowerInvariant(), actualETag.ToLowerInvariant(),
                        "Uploaded object ETag value is not expected");
                }
                catch (WebException)
                {
                    //TODO:
                }
            }
            finally
            {
                if (req != null) req.Abort();
                if (res != null) res.Close();
            }
        }

        [Test]
        public void PutPreSignedUriDefaultNegativeTest()
        {
            var testStr = FileUtils.GenerateOneKb();
            var bytes = Encoding.ASCII.GetBytes(testStr);

            HttpWebRequest req = null;
            HttpWebResponse res = null;

            var now = DateTime.Now;
            //set expiration time to 5 seconds before
            var expireDate = now.AddSeconds(-5);
            var targetObject = OssTestUtils.GetObjectKey(_className);
            var uri = _ossClient.GeneratePresignedUri(_bucketName, targetObject, expireDate, SignHttpMethod.Put);
            try
            {
                req = WebRequest.Create(uri) as HttpWebRequest;
                req.Method = "PUT";
                using (var stream = req.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
                res = req.GetResponse() as HttpWebResponse;
                Assert.Fail("response fail for expired URI");
            }
            catch (WebException e)
            {
                Assert.IsTrue(e.Message.Contains("403"),
                    string.Format("Unexpected exception: {0}", e.Message));
            }
            finally
            {
                if (req != null) req.Abort();
                if (res != null) res.Close();
            }
        }
        #endregion
    }
}

实例下载地址

阿里云 OSS上传下载文件 实例源码下载

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警