#region 分块上传方法
/// <summary>
/// 分块上传方法
/// </summary>
/// <param name="fullFilePath">要上传的文件路径</param>
/// <param name="endPoint"></param>
/// <param name="accessKeyID"></param>
/// <param name="accessKeySecret"></param>
/// <param name="bucketName"></param>
/// <param name="key"></param>
public static void MutiPartUpload(string fullFilePath, string endPoint, string accessKeyID , string accessKeySecret, string bucketName, string key)
{
OssClient ossClient = new OssClient(endPoint, accessKeyID, accessKeySecret);
InitiateMultipartUploadRequest initRequest =
new InitiateMultipartUploadRequest(bucketName, key);
InitiateMultipartUploadResult initResult = ossClient.InitiateMultipartUpload(initRequest); //总是在这句 连接超时返回错误
// 设置每块为 5M
int partSize = 1024 * 1024 * 5;
FileInfo partFile = new FileInfo(fullFilePath);
// 计算分块数目
int partCount = (int)(partFile.Length / partSize);
if (partFile.Length % partSize != 0)
{
partCount++;
}
// 新建一个List保存每个分块上传后的ETag和PartNumber
List<PartETag> partETags = new List<PartETag>();
for (int i = 0; i < partCount; i++)
{
// 获取文件流
using (FileStream fis = new FileStream(partFile.FullName, FileMode.Open))
{
// 跳到每个分块的开头
long skipBytes = partSize * i;
fis.Position = skipBytes;
// fis.skip(skipBytes);
// 计算每个分块的大小
long size = partSize < partFile.Length - skipBytes ?
partSize : partFile.Length - skipBytes;
// 创建UploadPartRequest,上传分块
UploadPartRequest uploadPartRequest = new UploadPartRequest(bucketName, key
, initResult.UploadId);
uploadPartRequest.InputStream = fis;
uploadPartRequest.PartSize = size;
uploadPartRequest.PartNumber = (i + 1);
UploadPartResult uploadPartResult = ossClient.UploadPart(uploadPartRequest);
// 将返回的PartETag保存到List中。
partETags.Add(uploadPartResult.PartETag);
}
}
CompleteMultipartUploadRequest completeReq = new CompleteMultipartUploadRequest(bucketName, key, initResult.UploadId);
foreach (PartETag partETag in partETags)
{
completeReq.PartETags.Add(partETag);
}
//完成分块上传
CompleteMultipartUploadResult completeResult = ossClient.CompleteMultipartUpload(completeReq);
// 返回最终文件的MD5,用于用户进行校验
// Console.WriteLine(completeResult.ETag);
}
#endregion
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。