123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- 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
- {
- /// <summary>
- /// 附件服务
- /// </summary>
- [Route("eap/api/[controller]/[action]")]
- [Authorize]
- [ApiController]
- public class AttachmentController : ControllerBase
- {
- private readonly IHostingEnvironment _hostingEnvironment;
- /// <summary>
- ///
- /// </summary>
- /// <param name="hostingEnvironment"></param>
- public AttachmentController(IHostingEnvironment hostingEnvironment)
- {
- _hostingEnvironment = hostingEnvironment;
- }
- /// <summary>
- /// 上传
- /// </summary>
- /// <returns></returns>
- [HttpPost]
- public async Task<EapResponse> 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];
- }
- }
- }
|