指定从OSS下载Object的请求参数。
Exemplo n.º 1
0
        private void DownloadPart(object state)
        {
            DownloadTaskParam taskParam = state as DownloadTaskParam;

            if (taskParam == null)
            {
                throw new ClientException("Internal error. The taskParam should be type of DownloadTaskParam");
            }
            DownloadObjectRequest request = taskParam.Request;
            ResumablePartContext  part    = taskParam.Part;
            EventHandler <StreamTransferProgressArgs> downloadProgressCallback = taskParam.DownloadProgressCallback;

            try
            {
                string fileName = GetTempDownloadFile(request);
                if (part.IsCompleted && File.Exists(fileName))
                {
                    return;
                }

                const int retryCount = 3;
                for (int i = 0; i < retryCount; i++)
                {
                    try
                    {
                        GetObjectRequest partRequest = request.ToGetObjectRequest();
                        partRequest.SetRange(part.Position, part.Position + part.Length - 1);
                        using (var partResult = _ossClient.GetObject(partRequest))
                        {
                            using (var fs = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                fs.Seek(part.Position, SeekOrigin.Begin);
                                long totalBytes = WriteTo(partResult.Content, fs);
                                if (totalBytes != part.Length)
                                {
                                    throw new OssException(string.Format("Part {0} returns {1} bytes. Expected size is {2} bytes",
                                                                         part.PartId, totalBytes, part.Length));
                                }
                                Interlocked.Add(ref _downloadedBytes, partResult.ContentLength);
                            }

                            part.IsCompleted = true;
                            return;
                        }
                    }
                    catch (Exception ex) // when the connection is closed while sending the data, it will run into ObjectDisposedException.
                    {
                        if (!(ex is ObjectDisposedException || ex is WebException) || i == retryCount - 1)
                        {
                            throw;
                        }
                    }
                }

                throw new ClientException("DownloadPart runs into internal error");
            }
            catch (Exception e)
            {
                taskParam.Error = e;
            }
            finally
            {
                taskParam.DownloadFinished.Set();
            }
        }
        public static void DownloadObjectUsingRange(IOss ossClient, string bucketName, string objectKeyName, string targetFile)
        {
            var length = ossClient.GetObjectMetadata(bucketName, objectKeyName).ContentLength;
            var goRequest = new GetObjectRequest(bucketName, objectKeyName);
            goRequest.SetRange(0, length / 2);
            var originalObject = ossClient.GetObject(goRequest);
            using (var requestStream = originalObject.Content)
            {
                using (var localfile = File.Open(targetFile, FileMode.OpenOrCreate))
                {
                    WriteTo(requestStream, localfile);
                }
            }

            goRequest.SetRange(length / 2 + 1, length -1);
            originalObject = ossClient.GetObject(goRequest);
            using (var requestStream = originalObject.Content)
            {
                using (var localfile = File.Open(targetFile, FileMode.Append))
                {
                    WriteTo(requestStream, localfile);
                }
            }
        }
        private static string GetOssImageObjectInfo(string bucket, string key)
        {
            GetObjectRequest request = new GetObjectRequest(_bucketName, _processedKey, "image/info");
            OssObject ossObject = _ossClient.GetObject(request);

            StringBuilder builder = new StringBuilder();
            using (var requestStream = ossObject.Content)
            {
                byte[] buf = new byte[1024];
                var len = 0;
                while ((len = requestStream.Read(buf, 0, 1024)) != 0)
                {
                    byte[] subBuf = new byte[len];
                    Buffer.BlockCopy(buf, 0, subBuf, 0, len);
                    builder.Append(Encoding.Default.GetString(subBuf));
                }
            }

            return builder.ToString();
        }
        public void ImageProcessTest()
        {
            try
            {
                // put example image
                _ossClient.PutObject(_bucketName, _keyName, _localImageFile);

                // get processed image
                GetObjectRequest request = new GetObjectRequest(_bucketName, _keyName, _process);
                OssObject ossObject = _ossClient.GetObject(request);

                // put processed image
                Stream seekableStream = ConvertStreamToSeekable(ossObject.Content);
                _ossClient.PutObject(_bucketName, _processedKey, seekableStream);

                // get info of processed image
                var imgInfo = GetOssImageObjectInfo(_bucketName, _processedKey);

                // check processed result
                Assert.AreEqual(imgInfo, _imageInfo);
            }
            finally
            {
                _ossClient.DeleteObject(_bucketName, _keyName);
                _ossClient.DeleteObject(_bucketName, _processedKey);
            }
        }
        public void UploadObjectWithFileSurfix2()
        {
            var key = OssTestUtils.GetObjectKey(_className);
            var newFileName = Path.GetDirectoryName(Config.UploadSampleFile) + "/newfile.m4u";

            try
            {
                File.Copy(Config.UploadSampleFile, newFileName, true);
                OssTestUtils.UploadObject(_ossClient, _bucketName, key, newFileName, null);
                Assert.IsTrue(OssTestUtils.ObjectExists(_ossClient, _bucketName, key));

                var coRequest = new GetObjectRequest(_bucketName, key);
                var result = _ossClient.GetObject(coRequest);
                Assert.AreEqual("video/vnd.mpegurl", result.Metadata.ContentType);
            }
            finally
            {
                if (OssTestUtils.ObjectExists(_ossClient, _bucketName, key))
                {
                    _ossClient.DeleteObject(_bucketName, key);
                    File.Delete(newFileName);
                }
            }
        }
        public void UploadObjectWithFileSurfixAndFileSurfix()
        {
            var key = OssTestUtils.GetObjectKey(_className) + ".potx";
            var newFileName = Path.GetDirectoryName(Config.UploadSampleFile) + "/newFile.docx";

            try
            {
                File.Copy(Config.UploadSampleFile, newFileName, true);
                OssTestUtils.UploadObject(_ossClient, _bucketName, key, newFileName, null);
                Assert.IsTrue(OssTestUtils.ObjectExists(_ossClient, _bucketName, key));

                var coRequest = new GetObjectRequest(_bucketName, key);
                var result = _ossClient.GetObject(coRequest);
                Assert.AreEqual("application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                                result.Metadata.ContentType);
            }
            finally
            {
                if (OssTestUtils.ObjectExists(_ossClient, _bucketName, key))
                {
                    _ossClient.DeleteObject(_bucketName, key);
                    File.Delete(newFileName);
                }
            }
        }
        public void GetObjectUnmodifiedSinceNegativeTest()
        {
            var coRequest = new GetObjectRequest(_bucketName, _objectKey);
            coRequest.UnmodifiedSinceConstraint = DateTime.UtcNow.AddDays(-1);

            try
            {
                _ossClient.GetObject(coRequest);
                Assert.Fail("Get object should not pass with UnmodifiedSince set to wrong value");
            }
            catch (OssException e)
            {
                Assert.AreEqual(OssErrorCode.PreconditionFailed, e.ErrorCode);
            }
        }
        public void GetObjectUnmodifiedSincePositiveTest()
        {
            var coRequest = new GetObjectRequest(_bucketName, _objectKey);
            coRequest.UnmodifiedSinceConstraint = DateTime.UtcNow.AddDays(1);

            _ossClient.GetObject(coRequest);
        }
        public void GetObjectNonMatchingETagPositiveTest()
        {
            var coRequest = new GetObjectRequest(_bucketName, _objectKey);
            coRequest.NonmatchingETagConstraints.Add("Dummy");

            _ossClient.GetObject(coRequest);
        }
        public void GetObjectNonMatchingETagNegativeTest()
        {
            var coRequest = new GetObjectRequest(_bucketName, _objectKey);
            coRequest.NonmatchingETagConstraints.Add(_objectETag);

            try
            {
                _ossClient.GetObject(coRequest);
                Assert.Fail("Get object should not pass with NonMatchingETag set to wrong value");
            }
            catch (OssException e)
            {
                Assert.AreEqual(OssErrorCode.NotModified, e.ErrorCode);
            }
        }
        public void GetObjectModifiedSinceNegativeTest()
        {
            var coRequest = new GetObjectRequest(_bucketName, _objectKey)
            {
                ModifiedSinceConstraint = DateTime.UtcNow.AddDays(1)
            };

            try
            {
                _ossClient.GetObject(coRequest);
                Assert.Fail("Get object should not pass with ModifiedSince set to wrong value");
            }
            //according to API, return 304
            catch (OssException e)
            {
                Assert.AreEqual(OssErrorCode.NotModified, e.ErrorCode);
            }
        }
        public void UploadObjectWithNoSurfix()
        {
            var key = OssTestUtils.GetObjectKey(_className) + "";
            try
            {
                using (var fs = File.Open(Config.UploadSampleFile, FileMode.Open))
                {
                    _ossClient.PutObject(_bucketName, key, fs, null);
                }

                Assert.IsTrue(OssTestUtils.ObjectExists(_ossClient, _bucketName, key));

                var coRequest = new GetObjectRequest(_bucketName, key);
                var result = _ossClient.GetObject(coRequest);
                Assert.AreEqual("application/octet-stream", result.Metadata.ContentType);
            }
            finally
            {
                if (OssTestUtils.ObjectExists(_ossClient, _bucketName, key))
                {
                    _ossClient.DeleteObject(_bucketName, key);
                }
            }
        }
        public void UploadObjectWithKeySurfixAndMetadata()
        {
            var key = OssTestUtils.GetObjectKey(_className) + ".js";
            try
            {
                var metadata = new ObjectMetadata();
                metadata.ContentType = "application/vnd.android.package-archive";

                using (var fs = File.Open(Config.UploadSampleFile, FileMode.Open))
                {
                    _ossClient.PutObject(_bucketName, key, fs, metadata);
                }

                Assert.IsTrue(OssTestUtils.ObjectExists(_ossClient, _bucketName, key));

                var coRequest = new GetObjectRequest(_bucketName, key);
                var result = _ossClient.GetObject(coRequest);
                Assert.AreEqual("application/vnd.android.package-archive", result.Metadata.ContentType);
            }
            finally
            {
                if (OssTestUtils.ObjectExists(_ossClient, _bucketName, key))
                {
                    _ossClient.DeleteObject(_bucketName, key);
                }
            }
        }