83 lines
2.8 KiB
C#
83 lines
2.8 KiB
C#
using Aliyun.OSS;
|
|
using Aliyun.OSS.Common;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
|
|
namespace New_College.Common
|
|
{
|
|
public class AliYunOssHelper
|
|
{
|
|
// private readonly static AliYunOssConfig ossConfig = GlobalData.AliYunOss;
|
|
|
|
/// <summary>
|
|
/// OSS下载
|
|
/// </summary>
|
|
/// <param name="downloadFilepath"></param>
|
|
/// <param name="filepath"></param>
|
|
/// <returns></returns>
|
|
public static string DownloadFile(string key, string filepath)
|
|
{
|
|
// 创建OssClient实例。
|
|
var client = new OssClient(AliYunOssConfig.endpoint, AliYunOssConfig.accessKeyId, AliYunOssConfig.accessKeySecret);
|
|
try
|
|
{
|
|
// 下载文件到流。OssObject 包含了文件的各种信息,如文件所在的存储空间、文件名、元信息以及一个输入流。
|
|
var obj = client.GetObject(AliYunOssConfig.bucket, filepath);
|
|
using (var requestStream = obj.Content)
|
|
{
|
|
byte[] buf = new byte[1024];
|
|
var fs = File.Open(key, FileMode.OpenOrCreate);
|
|
var len = 0;
|
|
// 通过输入流将文件的内容读取到文件或者内存中。
|
|
while ((len = requestStream.Read(buf, 0, 1024)) != 0)
|
|
{
|
|
fs.Write(buf, 0, len);
|
|
}
|
|
fs.Close();
|
|
}
|
|
Console.WriteLine("Get object succeeded");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine("Get object failed. {0}", ex.Message);
|
|
}
|
|
return "";
|
|
|
|
}
|
|
|
|
|
|
|
|
public static string UploadFile(string key, string filepath)
|
|
{
|
|
try
|
|
{
|
|
var conf = new ClientConfiguration();
|
|
//conf.ConnectionLimit = 512;
|
|
conf.MaxErrorRetry = 3;
|
|
conf.ConnectionTimeout = 10000*30;
|
|
conf.EnalbeMD5Check = true;
|
|
var client = new OssClient(AliYunOssConfig.endpoint, AliYunOssConfig.accessKeyId, AliYunOssConfig.accessKeySecret, conf);
|
|
try
|
|
{
|
|
// 上传文件。
|
|
var cc = client.PutObject(AliYunOssConfig.bucket, key, filepath);
|
|
var newurl = string.Format("{0}/{1}", AliYunOssConfig.wendpoint, key);
|
|
return newurl;
|
|
}
|
|
catch (ClientException ex)
|
|
{
|
|
Console.WriteLine("Put object failed, {0}", ex.Message);
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw ex;
|
|
}
|
|
return "";
|
|
}
|
|
}
|
|
}
|