예제 #1
0
        /**
         * 分块上传例子
         * **/
        private static bool uploadPart()
        {
            string path = @"you file path";//上传文件路径,例如E:\tool\aa.rar
            InitiateMultipartUploadResult result = multipartUp();
            FileInfo file           = new FileInfo(path);
            int      part           = 5 * 1024 * 1024;
            int      numBytesToRead = (int)file.Length;
            int      i    = 0;
            XElement root = new XElement("CompleteMultipartUpload");//初始化一个xml,以备分块上传完成后调用complete方法提交本次上传的文件以通知服务端合并分块

            //开始读取文件
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                while (numBytesToRead > 0)
                {
                    UploadPartRequest request = new UploadPartRequest(
                        result.getBucket(), result.getKey(), result.getUploadId(),
                        i + 1);
                    //每次读取5M文件内容,如果最后一次内容不及5M则按实际大小取值
                    int    count = Convert.ToInt32((i * part + part) > file.Length ? file.Length - i * part : part);
                    byte[] data  = new byte[count];
                    int    n     = fs.Read(data, 0, count);
                    request.setInputStream(new MemoryStream(data));
                    ProgressListener sampleListener = new SampleListener(count); //实例一个更新进度的监听类,实际使用中可自己定义实现
                    request.setProgressListener(sampleListener);
                    PartETag tag = ks3Client.uploadPart(request);                //上传本次分块内容
                    Console.WriteLine(tag.ToString());
                    if (n == 0)
                    {
                        break;
                    }
                    numBytesToRead -= n;

                    XElement partE = new XElement("Part");
                    partE.Add(new XElement("PartNumber", i + 1));
                    partE.Add(new XElement("ETag", tag.geteTag()));
                    root.Add(partE);
                    i++;
                }
            }
            //所有分块上传完成后发起complete request,通知服务端合并分块
            CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest(result.getBucket(), result.getKey(), result.getUploadId());

            completeRequest.setContent(new MemoryStream(System.Text.Encoding.Default.GetBytes(root.ToString())));
            CompleteMultipartUploadResult completeResult = ks3Client.completeMultipartUpload(completeRequest);

            return(true);
        }