//控制器
[HttpPost]
[Route("image/uploads")]
public async Task<string[]> Uploads()
{
// 检查是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new FileUploadException("请求的数据格式不正确");
}
var paths = await _uploader.Upload(Request.Content);
if (!paths.Any())
{
throw new FileUploadException("上传失败");
}
return paths;
}
[HttpPost]
[Route("image/uploadOss")]
public async Task<string> UploadOss()
{
var httpRequest = HttpContext.Current.Request;
// 检查是否是 multipart/form-data
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new FileUploadException("请求的数据格式不正确");
}
var paths = await _uploader.PutObjectFromFile(httpRequest);
if (!paths.Any())
{
throw new FileUploadException("上传失败");
}
return paths.First();
}
//api 接口
public async Task<string[]> Upload(HttpContent content)
{
//文件存储地址
string dirPath = BaseDirectory + RelativePath;
if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath);
// 采用MultipartMemoryStreamProvider
var provider = new CustomMultipartFormDataStreamProvider(dirPath);
try
{
// Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
await content.ReadAsMultipartAsync(provider);
var savePaths = provider.FileData.Select(p => RelativePath + Path.GetFileName(p.LocalFileName)).ToArray();
//对已保存的文件进行处理
var resultPaths = FileHandler(savePaths).Select(p => ServerHost + p).ToArray();
return resultPaths;
}
catch { return new string[] { }; }
}
/// <summary>
/// 上传文件到阿里云oss
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public async Task<string[]> PutObjectFromFile(HttpRequest content)
{
try
{
var pahts = new List<string>();
if (content.Files.Count <= 0) return pahts.ToArray();
foreach (string file in content.Files)
{
var postedFile = content.Files[file];
var path = RelativePath + DateTime.Now.ToString("yyyyMMddHHmmssfff")+"."+ postedFile.FileName.Split('.')[1];
client.PutObject(BucketName, path, postedFile.InputStream);
pahts.Add(Path.Combine("http://cczc-static.oss-cn-beijing.aliyuncs.com/", path));
}
return pahts.ToArray();
}
catch { return new string[] { }; }
}
//参数配置
protected static readonly string BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
protected static readonly string ServerHost = ConfigurationManager.AppSettings["ServerHost"];
protected static readonly string BucketName = ConfigurationManager.AppSettings["BucketName"];
/// <summary>
/// 文件上传相对路径,子类可重写
/// </summary>
/// <returns></returns>
protected virtual string RelativePath { get; } = $"upload/image/{DateTime.Today:yyyyMM/dd}/";
protected static string Endpoint { get; } = “你的阿里云访问域名”
protected static string AccessKeyId { get; } = AccessKeyId ;
protected static string AccessKeySecret { get; } = AccessKeySecret;
protected static OssClient client = new OssClient(Endpoint, AccessKeyId, AccessKeySecret);