原来是用的PutObject()方式上传文件的,但是当文件比较大的时候,总是报一个对方强制关闭连接导致上传失败。PS:公司的网比较渣,10MB的文件都传不上去,搜了下,说使用Multipart Upload方式上传比较好,经过一番折腾,终于搞定了。
使用的是Upload Part Copy拷贝上传上传的方式。
官方文档:http://docs.aliyun.com/?spm=5176.383663.9.6.tg4Xaf#/pub/oss/sdk/dotnet-sdk&multipart-upload
/// <summary>
/// 将文件保存到阿里云oss
/// </summary>
/// <param name="httpPostedFile">要保存的文件</param>
/// <param name="path">保存的文件路径</param>
/// <returns>上传文件的路径</returns>
public string SaveFile(HttpPostedFile httpPostedFile, string path)
{
//http://docs.aliyun.com/?spm=5176.383663.9.6.tg4Xaf#/pub/oss/sdk/dotnet-sdk&multipart-upload
string fileExt = Path.GetExtension(httpPostedFile.FileName);
string fileName = Path.Combine(path, Common.GetRamCode() + fileExt);
OssClient client = ALOssClient.GetInstance();
var bucketName = "wlx-zhibo";
var objectName = fileName;
// 开始Multipart Upload
var request = new InitiateMultipartUploadRequest(bucketName, fileName);
var r = client.InitiateMultipartUpload(request);
// 打印UploadId
Console.WriteLine(r.UploadId);
var partSize = 102400;
var fileSize = httpPostedFile.ContentLength;
var partCount = fileSize / partSize;
if (fileSize % partSize != 0)
{
partCount++;
}
var partETags = new List<PartETag>();
using (var inputStream = httpPostedFile.InputStream)
{
for (var i = 0; i < partCount; i++)
{
var skipBytes = (long)partSize * i;
inputStream.Seek(skipBytes, 0);
var size = (partSize < fileSize - skipBytes) ? partSize : (fileSize - skipBytes);
var req = new UploadPartRequest(bucketName, objectName, r.UploadId)
{
InputStream = inputStream,
PartSize = size,
PartNumber = i + 1
};
var uploadPart = client.UploadPart(req);
partETags.Add(uploadPart.PartETag);
}
}
var completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, r.UploadId);
foreach (var partETag in partETags)
{
completeMultipartUploadRequest.PartETags.Add(partETag);
}
var result = client.CompleteMultipartUpload(completeMultipartUploadRequest);
return result.Location;
}