121 lines
3.0 KiB
C#
121 lines
3.0 KiB
C#
using Aliyun.OSS;
|
|
using IRaCIS.Core.Infrastructure;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Options;
|
|
using NPOI.HPSF;
|
|
using SharpCompress.Common;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Drawing;
|
|
using System.Linq;
|
|
using System.Security.AccessControl;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace IRaCIS.Core.Application.Helper
|
|
{
|
|
|
|
public class AliyunOssOptions
|
|
{
|
|
public string RegionId { get; set; }
|
|
public string AccessKeyId { get; set; }
|
|
public string AccessKeySecret { get; set; }
|
|
public string EndPoint { get; set; }
|
|
public string BucketName { get; set; }
|
|
|
|
public string RoleArn { get;set; }
|
|
|
|
public string Region { get; set; }
|
|
|
|
public string ViewEndpoint { get; set; }
|
|
|
|
|
|
}
|
|
|
|
|
|
public interface IOSSService
|
|
{
|
|
|
|
}
|
|
|
|
public class OSSService : IOSSService
|
|
{
|
|
|
|
public AliyunOssOptions _OSSConfig { get; set; }
|
|
|
|
public OssClient _ossClient { get; set; }
|
|
|
|
|
|
|
|
public OSSService(IOptionsMonitor<AliyunOssOptions> options)
|
|
{
|
|
var ossOptions = options.CurrentValue;
|
|
|
|
_OSSConfig = new AliyunOssOptions()
|
|
{
|
|
RegionId = ossOptions.RegionId,
|
|
AccessKeyId = ossOptions.AccessKeyId,
|
|
AccessKeySecret = ossOptions.AccessKeySecret,
|
|
EndPoint = ossOptions.EndPoint,
|
|
BucketName = ossOptions.BucketName,
|
|
RoleArn = ossOptions.RoleArn,
|
|
Region = ossOptions.Region,
|
|
ViewEndpoint = ossOptions.ViewEndpoint
|
|
};
|
|
|
|
_ossClient = new OssClient(_OSSConfig.EndPoint, _OSSConfig.AccessKeyId, _OSSConfig.AccessKeySecret);
|
|
|
|
}
|
|
|
|
|
|
public string UploadToOSS(string localFilePath, string oosFolderPath)
|
|
{
|
|
var localFileName = Path.GetFileName(localFilePath);
|
|
|
|
var ossRelativePath = oosFolderPath + "/" + localFileName;
|
|
|
|
|
|
try
|
|
{
|
|
// 上传文件
|
|
var result = _ossClient.PutObject(_OSSConfig.BucketName, ossRelativePath, localFilePath);
|
|
|
|
return ossRelativePath;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw new BusinessValidationFailedException("oss上传失败" + ex.Message);
|
|
|
|
}
|
|
}
|
|
|
|
public void DownLoadFromOSS(string ossRelativePath, string localFilePath)
|
|
{
|
|
try
|
|
{
|
|
var result = _ossClient.GetObject(_OSSConfig.BucketName, ossRelativePath);
|
|
|
|
// 将下载的文件流保存到本地文件
|
|
using (var fs = File.OpenWrite(localFilePath))
|
|
{
|
|
result.Content.CopyTo(fs);
|
|
fs.Close();
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
throw new BusinessValidationFailedException("oss下载失败!" + ex.Message);
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|