C#调用阿里云OSS上传文件(分片)
首先从阿里云官网下载OSS的.NET SDK,然后在项目中添加引用Aliyun.OSS.dll
本例为分片上传方式,适用于上传比较大的文件。
引入命名空间:
using Aliyun.OSS; using Aliyun.OSS.Common;
定义阿里云OSS接口参数:
private string AccessKeyId = "xxx"; //阿里云AccessKeyId private string AccessKeySecret = "xxx"; //阿里云AccessKeySecret private string OssEndpoint = "http://oss-cn-xxx.aliyuncs.com"; //阿里云Endpoint private string OssBucket = "xxx"; //阿里云Bucket private static OssClient aliyunclient; //阿里云OSS连接对象 static int partSize = 50 * 1024 * 1024; //分片上传大小
创建阿里云OSS客户端连接:
aliyunclient = new OssClient(this.OssEndpoint, this.AccessKeyId, this.AccessKeySecret);
分片上传文件:
string remotefile = "path/to/aliyun/test.mp4"; //阿里云上目标文件 string localfile = "D:\\test.mp4"; //要上传的本地文件 try { var uploadId = InitiateMultipartUpload(this.OssBucket, remotefile); var partETags = UploadParts(this.OssBucket, remotefile, localfile, uploadId, partSize); CompleteUploadPart(this.OssBucket, remotefile, uploadId, partETags); bool doesexist = aliyunclient.DoesObjectExist(this.OssBucket, remotefile); if (doesexist) { this.logtext = "上传成功。"; } else { this.logtext = "上传失败。"; } } catch (OssException ex) { this.logtext = "上传失败," + ex.Message + "。"; }
分片上传函数定义:
private static string InitiateMultipartUpload(String bucketName, String objectName) { var request = new InitiateMultipartUploadRequest(bucketName, objectName); var result = aliyunclient.InitiateMultipartUpload(request); return result.UploadId; } private static List<PartETag> UploadParts(String bucketName, String objectName, String fileToUpload, String uploadId, int partSize) { var fi = new FileInfo(fileToUpload); var fileSize = fi.Length; var partCount = fileSize / partSize; if (fileSize % partSize != 0) { partCount++; } var partETags = new List<PartETag>(); using (var fs = File.Open(fileToUpload, FileMode.Open)) { for (var i = 0; i < partCount; i++) { var skipBytes = (long)partSize * i; fs.Seek(skipBytes, 0); var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes); var request = new UploadPartRequest(bucketName, objectName, uploadId) { InputStream = fs, PartSize = size, PartNumber = i + 1 }; var result = aliyunclient.UploadPart(request); partETags.Add(result.PartETag); } } return partETags; } private static CompleteMultipartUploadResult CompleteUploadPart(String bucketName, String objectName, String uploadId, List<PartETag> partETags) { var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId); foreach (var partETag in partETags) { completeMultipartUploadRequest.PartETags.Add(partETag); } return aliyunclient.CompleteMultipartUpload(completeMultipartUploadRequest); }
注意事项:
阿里云上目标文件路径开头不能是“/”