66 lines
2.3 KiB
C#
66 lines
2.3 KiB
C#
using Aliyun.OSS;
|
|
using Hncore.Infrastructure.Core.Web;
|
|
using Hncore.Infrastructure.Serializer;
|
|
using Hncore.Infrastructure.WebApi;
|
|
using Hncore.Pass.Oss.Request;
|
|
using Hncore.Pass.OSS.Model;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Configuration;
|
|
using System;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Hncore.Pass.Vpn.Service
|
|
{
|
|
public class UploadService
|
|
{
|
|
OssClient m_AliOssClient;
|
|
IConfiguration m_Configuration;
|
|
const string m_BucketName = "hncourse";
|
|
public UploadService(OssClient _AliOssClient, IConfiguration _Configuration)
|
|
{
|
|
m_AliOssClient = _AliOssClient;
|
|
m_Configuration = _Configuration;
|
|
}
|
|
public async Task<(string,string,Stream)> GetStreamFromRequest(HttpRequest reuest)
|
|
{
|
|
var name = "";
|
|
var fileKey = DateTime.Now.Ticks + new Random((int)DateTime.Now.Ticks).Next(0, 100000).ToString();
|
|
Stream stream = default(Stream);
|
|
//base64上传
|
|
if (reuest.ContentType.Contains("application/json"))
|
|
{
|
|
var body = await reuest.ReadBodyAsStringAsync();
|
|
var request = body.FromJsonTo<RequestBase<UploadImageBase64Request>>();
|
|
var base64 = request.Data.Base64;
|
|
byte[] imageByte = Convert.FromBase64String(base64);
|
|
stream = new MemoryStream(imageByte);
|
|
fileKey = $"{fileKey.ToString()}.jpg";
|
|
name = request.Data.Name;
|
|
}
|
|
else if (reuest.Form.Files.Any())
|
|
{
|
|
var file = reuest.Form.Files.First();
|
|
name = file.Name;
|
|
fileKey = $"{fileKey.ToString()}{Path.GetExtension(file.FileName)}";
|
|
stream = file.OpenReadStream();
|
|
}
|
|
return (fileKey, name,stream);
|
|
}
|
|
|
|
public UploadResult AliYunUpload(string key,string name, Stream stream)
|
|
{
|
|
var result = new UploadResult()
|
|
{
|
|
BaseUrl = string.Format("http://{0}.{1}", m_BucketName, m_Configuration["Aliyun:Oss:AliEndpoint"]),
|
|
Path = key,
|
|
OriginName = name
|
|
};
|
|
var ret = m_AliOssClient.PutObject(m_BucketName, key, stream);
|
|
|
|
return result;
|
|
}
|
|
}
|
|
}
|