using Cksoft.Unity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;
namespace DllEapBll.Controllers
{
///
/// 附件服务
///
[Route("eap/api/[controller]/[action]")]
[Authorize]
[ApiController]
public class AttachmentController : ControllerBase
{
private readonly IHostingEnvironment _hostingEnvironment;
///
///
///
///
public AttachmentController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
///
/// 上传
///
///
[HttpPost]
public async Task Upload()
{
var request = Request;
var file = request.Form.Files["file"];
var dateNow = DateTime.Now;
var extension = this.GetFileAExtension(file.FileName);
var fileNewName = Guid.NewGuid().ToString() + "." + extension;
Stream stream = new MemoryStream();
try
{
string path = $"/Upload/{dateNow.Year}/{dateNow.Month}/{dateNow.Day}/";
string phyicPath = _hostingEnvironment.WebRootPath + path;
string savedPath = phyicPath + fileNewName;
this.CreateDirectory(phyicPath);
stream = file.OpenReadStream();
byte[] bs = new byte[stream.Length];
stream.Read(bs, 0, bs.Length);
FileStream fs = new FileStream(savedPath, FileMode.CreateNew);
fs.Write(bs, 0, bs.Length);
await Task.CompletedTask;
return new EapResponse()
{
Code = 1,
Msg = path + fileNewName,
};
}
catch (Exception e)
{
return new EapResponse
{
Code = -1,
Msg = e.Message
};
}
finally
{
stream.Close();
}
}
private void CreateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
private string GetFileAExtension(string fileName)
{
var arr = fileName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
if (arr == null || arr.Length <= 0)
{
return null;
}
return arr[arr.Length - 1];
}
}
}