public static void AsyncCopyObject(string sourceBucket, string sourceKey, string targetBucket, string targetKey)
        {
            try
            {
                var metadata = new ObjectMetadata();
                metadata.AddHeader("mk1", "mv1");
                metadata.AddHeader("mk2", "mv2");
                var req = new CopyObjectRequest(sourceBucket, sourceKey, targetBucket, targetKey)
                {
                    NewObjectMetadata = metadata
                };
                client.BeginCopyObject(req, CopyObjectCallback, null);

                _event.WaitOne();
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                                  ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        public static void AsyncCopyObject(string sourceBucket, string sourceKey, string targetBucket, string targetKey)
        {
            try
            {
                var metadata = new ObjectMetadata();
                metadata.AddHeader("mk1", "mv1");
                metadata.AddHeader("mk2", "mv2");
                var req = new CopyObjectRequest(sourceBucket, sourceKey, targetBucket, targetKey)
                {
                    NewObjectMetadata = metadata
                };
                client.BeginCopyObject(req, CopyObjectCallback, null);

                _event.WaitOne();
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
Exemple #3
0
        public void PutObjectCallbackVarTest()
        {
            string callbackHeaderBuilder         = new CallbackHeaderBuilder(_callbackUrl, _callbackBody).Build();
            string CallbackVariableHeaderBuilder = new CallbackVariableHeaderBuilder().
                                                   AddCallbackVariable("x:var1", "x:value1").AddCallbackVariable("x:var2", "x:value2").Build();

            var metadata = new ObjectMetadata();

            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);
            metadata.AddHeader(HttpHeaders.CallbackVar, CallbackVariableHeaderBuilder);

            var putObjectResult = _ossClient.PutObject(_bucketName, _objectKey, Config.UploadTestFile, metadata);

            Assert.IsTrue(putObjectResult.IsSetResponseStream());
            Assert.AreEqual(_callbackOkResponse, GetCallbackResponse(putObjectResult));
            Assert.AreEqual(putObjectResult.HttpStatusCode, HttpStatusCode.OK);
            Assert.AreEqual(putObjectResult.ContentLength, _callbackOkResponse.Length);
            Assert.AreEqual(putObjectResult.RequestId.Length, "58DB0ACB686D42D5B4163D75".Length);
            Assert.AreEqual(putObjectResult.ResponseMetadata[HttpHeaders.ContentType], "application/json");
            Assert.AreEqual(putObjectResult.ResponseMetadata[HttpHeaders.ETag], putObjectResult.ETag);
            Assert.AreEqual(putObjectResult.ResponseMetadata[HttpHeaders.ContentMd5].Length, "7GoU4OYaYroKXsbsG1f/lw==".Length);
            Assert.IsTrue(putObjectResult.ResponseMetadata[HttpHeaders.HashCrc64Ecma].Length > 0);
            Assert.IsTrue(putObjectResult.ResponseMetadata[HttpHeaders.ServerElapsedTime].Length > 0);
            Assert.AreEqual(putObjectResult.ResponseMetadata[HttpHeaders.Date].Length, "Wed, 29 Mar 2017 01:15:58 GMT".Length);

            _ossClient.DeleteObject(_bucketName, _objectKey);
        }
Exemple #4
0
        /// <summary>
        /// 获得ObjectMetadata
        /// </summary>
        /// <param name="callbackUrl">回调地址</param>
        /// <param name="callbackBody"></param>
        /// <returns></returns>
        protected ObjectMetadata GetCallbackMetadata(string callbackUrl, string callbackBody)
        {
            string callbackHeaderBuilder         = new CallbackHeaderBuilder(callbackUrl, callbackBody).Build();
            string callbackVariableHeaderBuilder = new CallbackVariableHeaderBuilder().Build();
            var    metadata = new ObjectMetadata();

            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);
            metadata.AddHeader(HttpHeaders.CallbackVar, callbackVariableHeaderBuilder);
            return(metadata);
        }
        /// <summary>
        /// 完成回调处理
        /// </summary>
        /// <param name="callbackUrl"></param>
        /// <param name="callbackBody"></param>
        /// <returns></returns>
        private ObjectMetadata BuildCallbackMetadata(string callbackUrl, string callbackBody)
        {
            string callbackHeaderBuilder         = new CallbackHeaderBuilder(callbackUrl, callbackBody).Build();
            string CallbackVariableHeaderBuilder = new CallbackVariableHeaderBuilder().
                                                   AddCallbackVariable("x:var1", "x:value1").AddCallbackVariable("x:var2", "x:value2").Build();
            var metadata = new ObjectMetadata();

            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);
            metadata.AddHeader(HttpHeaders.CallbackVar, CallbackVariableHeaderBuilder);
            return(metadata);
        }
Exemple #6
0
        /// <summary>
        /// 上传文件到Oss
        /// </summary>
        /// <param name="bucketName">bucket名</param>
        /// <param name="Key">文件夹</param>
        /// <param name="FileByte">文件字节数组</param>
        /// <param name="fileExt">文件后缀</param>
        /// <param name="ossPoint">站点</param>
        /// <param name="accessId">accessId</param>
        /// <param name="accessKey">accessKey</param>
        /// <returns></returns>
        public static string UploadFileFromByte(string bucketName, string Key, byte[] FileByte, string fileExt,
                                                bool isExpires = true, bool isGzip = false)
        {
            if (string.IsNullOrWhiteSpace(bucketName))
            {
                throw new Exception("Bucket名称为空");
            }

            if (FileByte.Length == 0)
            {
                throw new Exception("请选择文件");
            }

            //建立Oss客户端连接
            OssClient client = ConnOssClient();

            if (!client.DoesBucketExist(bucketName))
            {
                throw new Exception("Bucket还没有建立");
            }

            //读入MemoryStream对象
            string fileExtension = fileExt.ToLower();

            //读入MemoryStream对象
            Stream stream = new MemoryStream(FileByte);

            //设置缓存
            ObjectMetadata Metadata = new ObjectMetadata();

            //Metadata.CacheControl = "Private";
            if (isExpires)
            {
                Metadata.CacheControl = string.Format("max-age={0}", 157680000);
            }
            else
            {
                Metadata.CacheControl = "Private";
            }
            //if (isExpires) Metadata.AddHeader("Expires", DateTime.MaxValue.GetDateTimeFormats('r')[0]);
            //if (isExpires) Metadata.AddHeader("Expires", 2628000);
            Metadata.AddHeader("Content-Type", FileContentTypeHelper.GetMimeType(fileExtension));
            if (isGzip)
            {
                Metadata.AddHeader("Content-Encoding", "gzip");
            }
            //上传文件到Oss
            client.PutObject(bucketName, Key, stream, Metadata);

            return(GetDomain() + "/" + Key);
        }
Exemple #7
0
        private ObjectMetadata Deserialize(HttpResponseMessage response)
        {
            var metadata = new ObjectMetadata();

            foreach (var header in response.Headers)
            {
                if (header.Key.StartsWith(OssHeaders.OssUserMetaPrefix, false, CultureInfo.InvariantCulture))
                {
                    // The key of user in the metadata should not contain the prefix.
                    metadata.UserMetadata.Add(header.Key.Substring(OssHeaders.OssUserMetaPrefix.Length),
                                              header.Value.FirstOrDefault());
                }
                else if (string.Equals(header.Key, HttpHeaders.ContentLength, StringComparison.InvariantCultureIgnoreCase))
                {
                    // Content-Length. Parse should not fail.
                    metadata.ContentLength = long.Parse(header.Value.FirstOrDefault(), CultureInfo.InvariantCulture);
                }
                else if (string.Equals(header.Key, HttpHeaders.ETag, StringComparison.InvariantCultureIgnoreCase))
                {
                    metadata.ETag = OssUtils.TrimETag(header.Value.FirstOrDefault());
                }
                else if (string.Equals(header.Key, HttpHeaders.LastModified, StringComparison.InvariantCultureIgnoreCase))
                {
                    metadata.LastModified = DateUtils.ParseRfc822Date(header.Value.FirstOrDefault());
                }
                else
                {
                    // Treat the other headers just as strings.
                    metadata.AddHeader(header.Key, header.Value);
                }
            }
            return(metadata);
        }
        public void SetObjectTaggingFromHeaderTest()
        {
            var key = OssTestUtils.GetObjectKey(_className);

            var tag1 = new Tag
            {
                Key   = "key1",
                Value = "value1"
            };

            var tag2 = new Tag
            {
                Key   = "key2",
                Value = "value2"
            };

            var meta = new ObjectMetadata();

            meta.AddHeader("x-oss-tagging", "key1=value1&key2=value2");

            var putRequest = new PutObjectRequest(_bucketName, key, new MemoryStream(Encoding.ASCII.GetBytes("hello world")));

            putRequest.Metadata = meta;
            _ossClient.PutObject(putRequest);

            var result = _ossClient.GetObjectTagging(_bucketName, key);

            Assert.AreEqual(result.Tags.Count, 2);
            Assert.AreEqual(result.Tags[0].Key, tag1.Key);
            Assert.AreEqual(result.Tags[0].Value, tag1.Value);
            Assert.AreEqual(result.Tags[1].Key, tag2.Key);
            Assert.AreEqual(result.Tags[1].Value, tag2.Value);
        }
Exemple #9
0
        public void ResumableUploadCallbackUriInvalidNegativeTest()
        {
            string callbackHeaderBuilder = new CallbackHeaderBuilder("https://wwww.aliyun.com/", _callbackBody).Build();

            var metadata = new ObjectMetadata();

            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);

            try
            {
                // use PutObject for small files
                _ossClient.ResumableUploadObject(_bucketName, _objectKey, Config.UploadTestFile, metadata, null);
                Assert.Fail("Put object callback should be not successfully with invald callback uri");
            }
            catch (OssException e)
            {
                Assert.AreEqual(OssErrorCode.CallbackFailed, e.ErrorCode);
                Assert.AreEqual("Error status : 502.", e.Message);
            }

            try
            {
                // use Multipart upload for big files
                _ossClient.ResumableUploadObject(_bucketName, _objectKey, Config.MultiUploadTestFile, metadata, null, 1024 * 1024);
                Assert.Fail("Put object callback should be not successfully with invald callback uri");
            }
            catch (OssException e)
            {
                Assert.AreEqual(OssErrorCode.CallbackFailed, e.ErrorCode);
                Assert.AreEqual("Error status : 502.", e.Message);
            }
        }
Exemple #10
0
        public void GeneratePresignedUriCallbackUriInvalidNegativeTest()
        {
            string callbackHeaderBuilder = new CallbackHeaderBuilder("https://wwww.aliyun.com/", _callbackBody).Build();

            var gpuRequest = new GeneratePresignedUriRequest(_bucketName, _objectKey, SignHttpMethod.Put)
            {
                Expiration = DateTime.Now.AddHours(1),
                Callback   = callbackHeaderBuilder
            };
            var uri = _ossClient.GeneratePresignedUri(gpuRequest);

            var metadata = new ObjectMetadata();

            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);

            try
            {
                _ossClient.PutObject(uri, Config.UploadTestFile, metadata);
                Assert.Fail("Put object callback should be not successfully with invald callback uri");
            }
            catch (OssException e)
            {
                Assert.AreEqual(OssErrorCode.CallbackFailed, e.ErrorCode);
                Assert.AreEqual("Error status : 502.", e.Message);
            }
            finally
            {
                _ossClient.DeleteObject(_bucketName, _objectKey);
            }
        }
Exemple #11
0
 public async Task SaveBlobStreamAsync(string containerName, string blobName, Stream source, BlobProperties properties = null)
 {
     try
     {
         await Task.Run(() =>
         {
             var exist = _ossClient.DoesBucketExist(containerName);
             if (!exist)
             {
                 _ossClient.CreateBucket(containerName);
             }
             var md5        = OssUtils.ComputeContentMd5(source, source.Length);
             var objectMeta = new ObjectMetadata();
             objectMeta.AddHeader("Content-MD5", md5);
             objectMeta.UserMetadata.Add("Content-MD5", md5);
             if (properties != null)
             {
                 objectMeta.ContentType = properties.ContentType;
             }
             _ossClient.PutObject(containerName, blobName, source, objectMeta);
         });
     }
     catch (Exception ex)
     {
         if (ex.IsOssStorageException())
         {
             throw ex.Convert();
         }
         throw;
     }
 }
        /// <summary>
        /// oss上传
        /// </summary>
        /// <param name="prepareInfo">酷安接口返回的信息</param>
        /// <param name="fileInfo">酷安接口返回的文件信息</param>
        /// <param name="stream">文件流</param>
        /// <param name="contentType">上传文件的imei类型</param>
        /// <returns>响应数据</returns>
        /// <exception cref="OssException">OSS异常</exception>
        /// <exception cref="Newtonsoft.Json.JsonSerializationException">JSON序列化异常</exception>
        public static Resp <OssUploadPictureResponse> OssUpload(
            OssUploadPicturePrepareResultUploadPrepareInfo prepareInfo,
            OssUploadPicturePrepareResultFileInfo fileInfo,
            Stream stream,
            string contentType,
            OssUploadProgressHandler progressHandler = null)
        {
            var oss = new Aliyun.OSS.OssClient(
                prepareInfo.EndPoint.Replace("https://", ""),
                prepareInfo.AccessKeyId,
                prepareInfo.AccessKeySecret,
                prepareInfo.SecurityToken
                );
            var callback = "eyJjYWxsYmFja0JvZHlUeXBlIjoiYXBwbGljYXRpb25cL2pzb24iLCJjYWxsYmFj" +
                           "a0hvc3QiOiJhcGkuY29vbGFway5jb20iLCJjYWxsYmFja1VybCI6Imh0dHBzOlwvXC9hcGkuY29vbGF" +
                           "way5jb21cL3Y2XC9jYWxsYmFja1wvbW9iaWxlT3NzVXBsb2FkU3VjY2Vzc0NhbGxiYWNrP2NoZWNrQX" +
                           "J0aWNsZUNvdmVyUmVzb2x1dGlvbj0wJnZlcnNpb25Db2RlPTIxMDIwMzEiLCJjYWxsYmFja0JvZHkiO" +
                           "iJ7XCJidWNrZXRcIjoke2J1Y2tldH0sXCJvYmplY3RcIjoke29iamVjdH0sXCJoYXNQcm9jZXNzXCI6" +
                           "JHt4OnZhcjF9fSJ9";
            var callbackVar = "eyJ4OnZhcjEiOiJmYWxzZSJ9";
            var metadata    = new ObjectMetadata {
                ContentMd5  = OssUtils.ComputeContentMd5(stream, stream.Length),
                ContentType = contentType
            };

            metadata.AddHeader(HttpHeaders.Callback, callback);
            metadata.AddHeader(HttpHeaders.CallbackVar, callbackVar);

            var request = new PutObjectRequest(
                prepareInfo.Bucket,
                fileInfo.UploadFileName,
                stream,
                metadata);

            request.StreamTransferProgress += (object sender, StreamTransferProgressArgs args) => {
                // 文件上传进度回调
                progressHandler?.Invoke(fileInfo, sender, args);
            };
            var putResult = oss.PutObject(request);

            // 相应数据
            var response = GetCallbackResponse(putResult);
            var jsonObj  = JsonConvert.DeserializeObject <Resp <OssUploadPictureResponse> >(response);

            return(jsonObj);
        }
Exemple #13
0
        public void GeneratePresignedUriCallbackTestWithParameter()
        {
            string callbackHeaderBuilder         = new CallbackHeaderBuilder(_callbackUrl, _callbackBody).Build();
            string CallbackVariableHeaderBuilder = new CallbackVariableHeaderBuilder().
                                                   AddCallbackVariable("x:var1", "x:value1").AddCallbackVariable("x:var2", "x:value2").Build();

            var gpuRequest = new GeneratePresignedUriRequest(_bucketName, _objectKey, SignHttpMethod.Put)
            {
                ContentType = "text/rtf",
                Expiration  = DateTime.Now.AddHours(1),
                Callback    = callbackHeaderBuilder,
                CallbackVar = CallbackVariableHeaderBuilder
            };

            gpuRequest.UserMetadata.Add("Author", "Mingdi");
            gpuRequest.AddQueryParam("x-param-null", "");
            gpuRequest.AddQueryParam("x-param-space0", " ");
            gpuRequest.AddQueryParam("x-param-value", "value");
            gpuRequest.AddQueryParam("x-param-space1", " ");
            var uri = _ossClient.GeneratePresignedUri(gpuRequest);

            var metadata = new ObjectMetadata();

            metadata.ContentType = "text/rtf";
            metadata.UserMetadata.Add("Author", "Mingdi");
            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);
            metadata.AddHeader(HttpHeaders.CallbackVar, CallbackVariableHeaderBuilder);

            var putObjectResult = _ossClient.PutObject(uri, Config.UploadTestFile, metadata);

            Assert.IsTrue(putObjectResult.IsSetResponseStream());
            Assert.AreEqual(_callbackOkResponse, GetCallbackResponse(putObjectResult));
            Assert.AreEqual(putObjectResult.HttpStatusCode, HttpStatusCode.OK);
            Assert.AreEqual(putObjectResult.ContentLength, _callbackOkResponse.Length);
            Assert.AreEqual(putObjectResult.RequestId.Length, "58DB0ACB686D42D5B4163D75".Length);
            Assert.AreEqual(putObjectResult.ResponseMetadata[HttpHeaders.ContentType], "application/json");
            Assert.AreEqual(putObjectResult.ResponseMetadata[HttpHeaders.ETag], putObjectResult.ETag);
            Assert.AreEqual(putObjectResult.ResponseMetadata[HttpHeaders.ContentMd5].Length, "7GoU4OYaYroKXsbsG1f/lw==".Length);
            Assert.IsTrue(putObjectResult.ResponseMetadata[HttpHeaders.HashCrc64Ecma].Length > 0);
            Assert.IsTrue(putObjectResult.ResponseMetadata[HttpHeaders.ServerElapsedTime].Length > 0);
            Assert.AreEqual(putObjectResult.ResponseMetadata[HttpHeaders.Date].Length, "Wed, 29 Mar 2017 01:15:58 GMT".Length);

            _ossClient.DeleteObject(_bucketName, _objectKey);
        }
Exemple #14
0
        /// <summary>
        /// 上传文件到Oss
        /// </summary>
        /// <param name="bucketName">bucket名</param>
        /// <param name="dir">文件夹</param>
        /// <param name="userId">用户ID</param>
        /// <param name="fileType">文件类型</param>
        /// <param name="file">文件</param>
        /// <param name="ossPoint">站点</param>
        /// <param name="accessId">accessId</param>
        /// <param name="accessKey">accessKey</param>
        /// <param name="newFileName">是否新文件名 默认生成新文件名</param>
        /// <returns></returns>
        public static string UploadFile(string bucketName, string dir, string userId, string fileType, HttpPostedFile file, bool newFileName = true)
        {
            if (string.IsNullOrWhiteSpace(bucketName))
            {
                throw new Exception("Bucket名称为空");
            }
            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new Exception("userId为空");
            }
            if (string.IsNullOrWhiteSpace(fileType))
            {
                throw new Exception("fileType为空");
            }

            if (file == null || string.IsNullOrWhiteSpace(file.FileName))
            {
                throw  new Exception("请选择文件");
            }

            //建立Oss客户端连接
            OssClient client = ConnOssClient();

            if (!client.DoesBucketExist(bucketName))
            {
                throw  new Exception("Bucket还没有建立");
            }

            string fileName = file.FileName;

            string fileExtension = Path.GetExtension(fileName).ToLower();

            //文件保存Key生成
            string Key = dir + "/" + userId + "/" + fileType + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + Guid.NewGuid().ToString("N").ToUpper() + fileExtension;

            if (!newFileName)//保留原文件名
            {
                Key = dir + "/" + userId + "/" + fileType + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + fileName;
            }
            //设置缓存
            ObjectMetadata Metadata = new ObjectMetadata();

            //Metadata.CacheControl = "Private";
            Metadata.CacheControl = string.Format("max-age={0}", 157680000);
            //Metadata.AddHeader("Expires", DateTime.MaxValue.GetDateTimeFormats('r')[0]);
            //Metadata.AddHeader("Expires", 2628000);
            Metadata.AddHeader("Content-Type", FileContentTypeHelper.GetMimeType(fileExtension));

            //上传文件到Oss
            PutObjectResult putResult = client.PutObject(bucketName, Key, file.InputStream, Metadata);

            return(GetDomain() + "/" + Key);
        }
Exemple #15
0
        /// <summary>
        /// 得到新的ObjectMetadata(从原来旧的基础上)
        /// </summary>
        /// <param name="sourceObjectMetadata"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        internal static ObjectMetadata GetObjectMetadataBySourceObjectMetadata(ObjectMetadata sourceObjectMetadata,
                                                                               string key,
                                                                               string value)
        {
            ObjectMetadata objectMetadata = new ObjectMetadata();

            if (key != "CacheControl")
            {
                objectMetadata.CacheControl = sourceObjectMetadata.CacheControl;
            }

            if (key != "ContentDisposition")
            {
                objectMetadata.ContentDisposition = sourceObjectMetadata.ContentDisposition;
            }

            if (key != "ContentEncoding")
            {
                objectMetadata.ContentEncoding = sourceObjectMetadata.ContentEncoding;
            }

            if (key != "ContentLength")
            {
                objectMetadata.ContentLength = sourceObjectMetadata.ContentLength;
            }

            if (key != "ContentMd5")
            {
                objectMetadata.ContentMd5 = sourceObjectMetadata.ContentMd5;
            }

            if (key != "Crc64")
            {
                objectMetadata.Crc64 = sourceObjectMetadata.Crc64;
            }

            if (key != "ETag")
            {
                objectMetadata.ETag = sourceObjectMetadata.ETag;
            }

            if (key != "ExpirationTime")
            {
                objectMetadata.ExpirationTime = sourceObjectMetadata.ExpirationTime;
            }

            if (objectMetadata.HttpMetadata.Any(x => x.Key != key))
            {
                objectMetadata.AddHeader(key, value);
            }

            return(objectMetadata);
        }
Exemple #16
0
        /// <summary>
        /// 上传文件到Oss
        /// </summary>
        /// <param name="bucketName">bucket名</param>
        /// <param name="dir">文件夹</param>
        /// <param name="userId">用户ID</param>
        /// <param name="fileType">文件类型</param>
        /// <param name="base64Str">文件Base64字符串</param>
        /// <param name="fileExt">文件后缀</param>
        /// <param name="ossPoint">站点</param>
        /// <param name="accessId">accessId</param>
        /// <param name="accessKey">accessKey</param>
        /// <returns></returns>
        public static string UploadFileFromBase64(string bucketName, string dir, string userId, string fileType, string base64Str, string fileExt)
        {
            if (string.IsNullOrWhiteSpace(bucketName))
            {
                throw new Exception("Bucket名称为空");
            }
            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new Exception("userId为空");
            }
            if (string.IsNullOrWhiteSpace(fileType))
            {
                throw new Exception("fileType为空");
            }

            if (string.IsNullOrWhiteSpace(base64Str))
            {
                throw new Exception("请选择文件");
            }

            //建立Oss客户端连接
            OssClient client = ConnOssClient();

            if (!client.DoesBucketExist(bucketName))
            {
                throw new Exception("Bucket还没有建立");
            }

            byte[] imageBytes = Convert.FromBase64String(base64Str);
            //读入MemoryStream对象
            Stream stream = new MemoryStream(imageBytes);

            string fileExtension = fileExt.ToLower();

            //文件保存Key生成
            string Key = dir + "/" + userId + "/" + fileType + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + Guid.NewGuid().ToString("N").ToUpper() + fileExtension;

            //设置缓存
            ObjectMetadata Metadata = new ObjectMetadata();

            //Metadata.CacheControl = "Private";
            Metadata.CacheControl = string.Format("max-age={0}", 157680000);
            //Metadata.AddHeader("Expires", DateTime.MaxValue.GetDateTimeFormats('r')[0]);
            //Metadata.AddHeader("Expires", 2628000);
            Metadata.AddHeader("Content-Type", FileContentTypeHelper.GetMimeType(fileExtension));

            //上传文件到Oss
            client.PutObject(bucketName, Key, stream, Metadata);

            return(GetDomain() + "/" + Key);
        }
 public static void CopyObject()
 {
     try
     {
         var metadata = new ObjectMetadata();
         metadata.AddHeader("mk1", "mv1");
         metadata.AddHeader("mk2", "mv2");
         var req = new CopyObjectRequest(sourceBucket, sourceKey, targetBucket, targetKey)
         {
             NewObjectMetadata = metadata
         };
         var ret = client.CopyObject(req);
         Console.WriteLine("target key's etag: " + ret.ETag);
     }
     catch (OssException ex)
     {
         Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                           ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Failed with error info: {0}", ex.Message);
     }
 }
 public static void CopyObject()
 {
     try
     {
         var metadata = new ObjectMetadata();
         metadata.AddHeader("mk1", "mv1");
         metadata.AddHeader("mk2", "mv2");
         var req = new CopyObjectRequest(sourceBucket, sourceKey, targetBucket, targetKey)
         {
             NewObjectMetadata = metadata
         };
         var ret = client.CopyObject(req);
         Console.WriteLine("target key's etag: " + ret.ETag);
     }
     catch (OssException ex)
     {
         Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
             ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Failed with error info: {0}", ex.Message);
     }
 }
Exemple #19
0
        /// <summary>
        /// 上传文件到Oss 文件名不变
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="bucketName">bucket名</param>
        /// <param name="dir">文件夹</param>
        /// <param name="userId">用户ID</param>
        /// <param name="fileType">文件类型</param>
        /// <param name="FileStream">文件流</param>
        /// <param name="fileExt">文件后缀</param>
        /// <param name="ossPoint">站点</param>
        /// <param name="accessId">accessId</param>
        /// <param name="accessKey">accessKey</param>
        /// <returns></returns>
        public static string UploadFileFromStream(string fileName, string bucketName, string dir, string userId, string fileType, Stream FileStream)
        {
            if (string.IsNullOrWhiteSpace(bucketName))
            {
                throw new Exception("Bucket名称为空");
            }
            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new Exception("userId为空");
            }
            if (string.IsNullOrWhiteSpace(fileType))
            {
                throw new Exception("fileType为空");
            }

            if (FileStream.Length == 0)
            {
                throw new Exception("请选择文件");
            }

            //建立Oss客户端连接
            OssClient client = ConnOssClient();

            if (!client.DoesBucketExist(bucketName))
            {
                throw new Exception("Bucket还没有建立");
            }

            //读入MemoryStream对象
            string fileExtension = Path.GetExtension(fileName);

            //文件保存Key生成
            string key = dir + "/" + userId + "/" + fileType + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + fileName;

            //设置缓存
            ObjectMetadata Metadata = new ObjectMetadata();

            //Metadata.CacheControl = "Private";
            Metadata.CacheControl = string.Format("max-age={0}", 157680000);
            //Metadata.AddHeader("Expires", DateTime.MaxValue.GetDateTimeFormats('r')[0]);
            //Metadata.AddHeader("Expires", 2628000);
            Metadata.AddHeader("Content-Type", FileContentTypeHelper.GetMimeType(fileExtension));

            //上传文件到Oss
            client.PutObject(bucketName, key, FileStream, Metadata);

            return(GetDomain() + "/" + key);
        }
Exemple #20
0
 public static void UploadFileExistBucketName(string key, string filePath)
 {
     try
     {
         // 初始化OssClient
         var            client = new OssClient(Tools.AliYunTools._ossEndpointURL, OSSACCESSKEYID, ACCESSKEYSECRET);
         ObjectMetadata media  = new ObjectMetadata();
         media.AddHeader("Content-Type", GetContentType(key));
         client.PutObject(Tools.AliYunTools._ossBucketName, key, filePath, media);
     }
     catch (Exception ex)
     {
         // IOHelper.LogText(string.Format("Put object failed, {0}", ex));
         throw new Exception(string.Format("Put object failed, {0}", ex.Message));
     }
 }
Exemple #21
0
        public static void UploadFile(string key, string filePath, out string msg)
        {
            try
            {
                msg = string.Empty;
                // 初始化OssClient
                var client = new OssClient(Tools.AliYunTools._ossEndpointURL, OSSACCESSKEYID, ACCESSKEYSECRET);

                ObjectMetadata media = new ObjectMetadata();
                media.AddHeader("Content-Type", GetContentType(key));
                client.PutObject(Tools.AliYunTools._ossBucketName, key, filePath, media);
            }
            catch (Exception ex)
            {
                msg = string.Format("Put object failed, {0}", ex.Message);
            }
        }
Exemple #22
0
        public void PutObjectCallbackUriInvalidNegativeTest()
        {
            string callbackHeaderBuilder = new CallbackHeaderBuilder("https://wwww.aliyun.com/", _callbackBody).Build();

            var metadata = new ObjectMetadata();

            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);

            try
            {
                _ossClient.PutObject(_bucketName, _objectKey, Config.UploadTestFile, metadata);
                Assert.Fail("Put object callback should be not successfully with invald callback uri");
            }
            catch (OssException e)
            {
                Assert.AreEqual(OssErrorCode.CallbackFailed, e.ErrorCode);
                Assert.AreEqual("Error status : 502.", e.Message);
            }
        }
Exemple #23
0
        public void CopyFile(string sourcePath, string targetPath, NameValueCollection metadata)
        {
            var sdfs = _GetDfsPath(sourcePath);
            var tdfs = _GetDfsPath(targetPath);

            var newMetadata = new ObjectMetadata();

            foreach (string item in metadata)
            {
                newMetadata.AddHeader(item, metadata[item]);
            }
            try
            {
                OssService.Instance.CopyObject(sdfs.Bucket, sdfs.path, tdfs.Bucket, tdfs.path, newMetadata);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }
 /// <inheritdoc/>
 public async Task SaveBlobStream(string containerName, string blobName, Stream source)
 {
     try
     {
         await Task.Run(() =>
         {
             var key        = $"{containerName}/{blobName}";
             var md5        = OssUtils.ComputeContentMd5(source, source.Length);
             var objectMeta = new ObjectMetadata();
             objectMeta.AddHeader("Content-MD5", md5);
             objectMeta.UserMetadata.Add("Content-MD5", md5);
             _ossClient.PutObject(_cfg.BucketName, key, source, objectMeta).HandlerError("上传对象出错");
         });
     }
     catch (Exception ex)
     {
         throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
                                    new Exception(ex.ToString()));
     }
 }
 public bool CopyObect(string sourceKey, string targetBucket, string targetKey)
 {
     try
     {
         var metadata = new ObjectMetadata();
         metadata.AddHeader(Aliyun.OSS.Util.HttpHeaders.ContentType, "text/html");
         var req = new CopyObjectRequest(bucketName, sourceKey, targetBucket, targetKey)
         {
             NewObjectMetadata = metadata
         };
         var ret = client.CopyObject(req);
         if (ret.HttpStatusCode == System.Net.HttpStatusCode.OK)
         {
             return(true);
         }
         return(false);
     }
     catch (OssException ex)
     {
         lastError = ex;
         return(false);
     }
 }
 /// <summary>
 ///     保存对象到指定的容器
 /// </summary>
 /// <param name="containerName"></param>
 /// <param name="blobName"></param>
 /// <param name="source"></param>
 public async Task SaveBlobStream(string containerName, string blobName, Stream source)
 {
     try
     {
         await Task.Run(() =>
         {
             var exist = _ossClient.DoesBucketExist(containerName);
             if (!exist)
             {
                 _ossClient.CreateBucket(containerName);
             }
             var md5        = OssUtils.ComputeContentMd5(source, source.Length);
             var objectMeta = new ObjectMetadata();
             objectMeta.AddHeader("Content-MD5", md5);
             objectMeta.UserMetadata.Add("Content-MD5", md5);
             _ossClient.PutObject(containerName, blobName, source, objectMeta);
         });
     }
     catch (Exception ex)
     {
         throw new StorageException(StorageErrorCode.PostError.ToStorageError(),
                                    new Exception(ex.ToString()));
     }
 }
Exemple #27
0
        /// <summary>
        /// 上传文件到Oss
        /// </summary>
        /// <param name="bucketName">bucket名</param>
        /// <param name="dir">文件夹</param>
        /// <param name="userId">用户ID</param>
        /// <param name="fileType">文件类型</param>
        /// <param name="relPath">服务器相对路径</param>
        /// <param name="physicalPath">服务器物理路径</param>
        /// <param name="ossPoint">站点</param>
        /// <param name="accessId">accessId</param>
        /// <param name="accessKey">accessKey</param>
        /// <returns></returns>
        public static string UploadFile(string bucketName, string dir, string userId, string fileType, string relPath, string physicalPath = "")
        {
            if (string.IsNullOrWhiteSpace(bucketName))
            {
                throw new Exception("Bucket名称为空");
            }
            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new Exception("userId为空");
            }
            if (string.IsNullOrWhiteSpace(fileType))
            {
                throw new Exception("fileType为空");
            }

            // if (file == null || string.IsNullOrWhiteSpace(file.FileName)) throw new Exception("请选择文件");

            //建立Oss客户端连接
            OssClient client = ConnOssClient();

            if (!client.DoesBucketExist(bucketName))
            {
                throw new Exception("Bucket还没有建立");
            }
            FileStream file;
            string     fileExtension;

            if (!string.IsNullOrEmpty(physicalPath))
            {
                fileExtension = Path.GetExtension(physicalPath).ToLower();
                file          = System.IO.File.OpenRead(physicalPath);
            }
            else
            {
                fileExtension = Path.GetExtension(relPath).ToLower();
                file          = System.IO.File.OpenRead(HttpContext.Current.Server.MapPath(relPath));
            }
            //string fileName = file.FileName;



            //文件保存Key生成
            string Key = dir + "/" + userId + "/" + fileType + "/" + DateTime.Now.ToString("yyyyMMdd") + "/" + Guid.NewGuid().ToString("N").ToUpper() + fileExtension;

            //设置缓存
            ObjectMetadata Metadata = new ObjectMetadata();

            //Metadata.CacheControl = "Private";
            Metadata.CacheControl = string.Format("max-age={0}", 157680000);
            //Metadata.AddHeader("Expires", DateTime.MaxValue.GetDateTimeFormats('r')[0]);
            //Metadata.AddHeader("Expires", 2628000);
            Metadata.AddHeader("Content-Type", FileContentTypeHelper.GetMimeType(fileExtension));

            //using (StreamWriter sw = new StreamWriter(@"C:\MonitorHandlerException.txt", true, Encoding.UTF8))
            //{
            //    sw.WriteLine(string.Format("{0} 上传ossKey:{1}bucketName:{2} FileLeng{3}", DateTime.Now.ToString(), Key,bucketName,file.Length));

            //}
            //上传文件到Oss
            PutObjectResult putResult = client.PutObject(bucketName, Key, file, Metadata);

            return(GetDomain() + "/" + Key);
        }
Exemple #28
0
        public void MultipartUploadCallbackUriInvalidNegativeTest()
        {
            // initiates a multipart upload
            var initRequest = new InitiateMultipartUploadRequest(_bucketName, _bigObjectKey);
            var initResult  = _ossClient.InitiateMultipartUpload(initRequest);

            // set part size 1MB
            const int partSize = 1024 * 1024 * 1;
            var       partFile = new FileInfo(Config.MultiUploadTestFile);
            // sets part count
            var partCount = OssTestUtils.CalculatePartCount(partFile.Length, partSize);

            var partETags = new List <PartETag>();

            //upload the file
            using (var fs = new FileStream(partFile.FullName, FileMode.Open))
            {
                for (var i = 0; i < partCount; i++)
                {
                    // skip to start position of each part
                    long skipBytes = partSize * i;
                    fs.Position = skipBytes;

                    // sets the part size
                    var size = partSize < partFile.Length - skipBytes
                        ? partSize
                        : partFile.Length - skipBytes;

                    // creates a UploadPartRequest, uploading parts
                    var uploadPartRequest = new UploadPartRequest(_bucketName, _bigObjectKey, initResult.UploadId)
                    {
                        InputStream = fs,
                        PartSize    = size,
                        PartNumber  = (i + 1)
                    };
                    var uploadPartResult = _ossClient.UploadPart(uploadPartRequest);

                    // saves the result to the list
                    partETags.Add(uploadPartResult.PartETag);
                }
            }

            var completeRequest = new CompleteMultipartUploadRequest(_bucketName, _bigObjectKey, initResult.UploadId);

            foreach (var partETag in partETags)
            {
                completeRequest.PartETags.Add(partETag);
            }

            string callbackHeaderBuilder = new CallbackHeaderBuilder("https://wwww.aliyun.com/", _callbackBody).Build();
            var    metadata = new ObjectMetadata();

            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);
            completeRequest.Metadata = metadata;

            try
            {
                _ossClient.CompleteMultipartUpload(completeRequest);
                Assert.Fail("Multipart upload callback should be not successfully with invald callback uri");
            }
            catch (OssException e)
            {
                Assert.AreEqual(OssErrorCode.CallbackFailed, e.ErrorCode);
                Assert.AreEqual("Error status : 502.", e.Message);
            }
            finally
            {
                _ossClient.DeleteObject(_bucketName, _bigObjectKey);
            }
        }
Exemple #29
0
        public void MultipartUploadCallbackVarTest()
        {
            // Initiate a multipart upload
            var initRequest = new InitiateMultipartUploadRequest(_bucketName, _bigObjectKey);
            var initResult  = _ossClient.InitiateMultipartUpload(initRequest);

            // Sets the part size as 1M
            const int partSize = 1024 * 1024 * 1;
            var       partFile = new FileInfo(Config.MultiUploadTestFile);
            // Calculates the part count
            var partCount = OssTestUtils.CalculatePartCount(partFile.Length, partSize);

            // creates a list of PartETag
            var partETags = new List <PartETag>();

            //upload the file
            using (var fs = new FileStream(partFile.FullName, FileMode.Open))
            {
                for (var i = 0; i < partCount; i++)
                {
                    // skip to the start of each part
                    long skipBytes = partSize * i;
                    fs.Position = skipBytes;

                    // calculates the part size
                    var size = partSize < partFile.Length - skipBytes
                        ? partSize
                        : partFile.Length - skipBytes;

                    // uploads the part
                    var uploadPartRequest = new UploadPartRequest(_bucketName, _bigObjectKey, initResult.UploadId)
                    {
                        InputStream = fs,
                        PartSize    = size,
                        PartNumber  = (i + 1)
                    };
                    var uploadPartResult = _ossClient.UploadPart(uploadPartRequest);

                    // adds the result to the list
                    partETags.Add(uploadPartResult.PartETag);
                }
            }

            string callbackHeaderBuilder         = new CallbackHeaderBuilder(_callbackUrl, _callbackBody).Build();
            string CallbackVariableHeaderBuilder = new CallbackVariableHeaderBuilder().
                                                   AddCallbackVariable("x:var1", "x:value1").AddCallbackVariable("x:var2", "x:value2").Build();
            var metadata = new ObjectMetadata();

            metadata.AddHeader(HttpHeaders.Callback, callbackHeaderBuilder);
            metadata.AddHeader(HttpHeaders.CallbackVar, CallbackVariableHeaderBuilder);

            var completeRequest = new CompleteMultipartUploadRequest(_bucketName, _bigObjectKey, initResult.UploadId);

            completeRequest.Metadata = metadata;
            foreach (var partETag in partETags)
            {
                completeRequest.PartETags.Add(partETag);
            }
            var completeMultipartUploadResult = _ossClient.CompleteMultipartUpload(completeRequest);

            Assert.IsTrue(completeMultipartUploadResult.IsSetResponseStream());
            Assert.AreEqual(_callbackOkResponse, GetCallbackResponse(completeMultipartUploadResult));
            Assert.AreEqual(completeMultipartUploadResult.HttpStatusCode, HttpStatusCode.OK);
            Assert.AreEqual(completeMultipartUploadResult.ContentLength, _callbackOkResponse.Length);
            Assert.AreEqual(completeMultipartUploadResult.RequestId.Length, "58DB0ACB686D42D5B4163D75".Length);
            Assert.AreEqual(completeMultipartUploadResult.ResponseMetadata[HttpHeaders.ContentType], "application/json");
            Assert.AreEqual(completeMultipartUploadResult.ResponseMetadata[HttpHeaders.ETag], completeMultipartUploadResult.ETag);
            Assert.IsFalse(completeMultipartUploadResult.ResponseMetadata.ContainsKey(HttpHeaders.ContentMd5));
            Assert.IsTrue(completeMultipartUploadResult.ResponseMetadata[HttpHeaders.HashCrc64Ecma].Length > 0);
            Assert.IsTrue(completeMultipartUploadResult.ResponseMetadata[HttpHeaders.ServerElapsedTime].Length > 0);
            Assert.AreEqual(completeMultipartUploadResult.ResponseMetadata[HttpHeaders.Date].Length, "Wed, 29 Mar 2017 01:15:58 GMT".Length);

            //delete the object
            _ossClient.DeleteObject(_bucketName, _bigObjectKey);
        }
Exemple #30
0
        public string AddFile(string path, Stream data, NameValueCollection userMetadata)
        {
            var    dfs             = _GetDfsPath(path);
            var    bucket          = dfs.Bucket;
            var    skey            = dfs.path.Replace("\\", "/").ToLower().TrimStart('/');
            string applicationName = dfs.ApplicationName;
            var    metadata        = new ObjectMetadata();

            if (!String.IsNullOrEmpty(applicationName))
            {
                var conf = DfsConfig.Instance[applicationName];
                if (conf != null)
                {
                    metadata.CacheControl    = conf.CacheControl;
                    metadata.ContentEncoding = conf.ContentEncoding;
                    if (conf.Expires > 0)
                    {
                        metadata.AddHeader(HttpHeaders.Expires, DateTime.Now.AddSeconds(conf.Expires));
                    }
                }
            }

            if (userMetadata != null && userMetadata.Count > 0)
            {
                string cc = userMetadata[HttpHeaders.CacheControl];
                if (!string.IsNullOrEmpty(cc))
                {
                    metadata.CacheControl = userMetadata[HttpHeaders.CacheControl];
                }
                var ce = userMetadata[HttpHeaders.ContentEncoding];
                if (!string.IsNullOrEmpty(ce))
                {
                    metadata.ContentEncoding = ce;
                }

                var cd = userMetadata[HttpHeaders.ContentDisposition];
                if (!string.IsNullOrEmpty(cd))
                {
                    metadata.ContentDisposition = cd;
                }

                var ct = userMetadata[HttpHeaders.ContentType];
                if (!string.IsNullOrEmpty(ct))
                {
                    metadata.ContentType = ct;
                }

                var md5 = userMetadata[HttpHeaders.ContentMd5];
                if (!string.IsNullOrEmpty(md5))
                {
                    metadata.ContentMd5 = md5;
                }


                foreach (string key in userMetadata.AllKeys)
                {
                    var v = userMetadata[key];


                    metadata.UserMetadata.Add(key, v);
                }
            }
            metadata.ContentLength = data.Length;
            if (String.IsNullOrEmpty(metadata.ContentType))
            {
                var contentType = Mime.Lookup(skey);
                metadata.ContentType = contentType;
            }
            try
            {
                var result = OssService.Instance.PutObject(bucket, skey, data, metadata);
                return(result.ETag);
            }
            catch (Exception ex)
            {
                log.Error(new Exception(path, ex));
                return(String.Empty);
            }
        }