using Cksoft.Unity; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace WebUpload.Controllers { [Route("eap/api/[controller]/[action]")] public class UploadController : ControllerBase { //public IActionResult Index() //{ // return View(); //} private readonly IHostingEnvironment _hostingEnvironment; public UploadController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } [HttpPost] public EapResponse Uploadfile([FromBody] CmkFile json) { byte[] byteArray = json.Bt; string upLoadDir = AppConfigurtaionServices.Configuration["upload"]; var dateNow = DateTime.Now; var fileNewName = ""; if (json.Extension.Contains("xls") || json.Extension.Contains("xlsx")) { fileNewName = json.FileName + "." + json.Extension; } else { fileNewName = Guid.NewGuid().ToString() + "." + json.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); byte[] bs = byteArray; stream.Read(bs, 0, bs.Length); using (FileStream fs = new FileStream(savedPath, FileMode.Create)) { fs.Write(bs, 0, bs.Length); return new EapResponse { Code = 1, Data = path + fileNewName, Msg = json.FileName + "," + upLoadDir }; } } catch (Exception e) { return new EapResponse { Code = -1, Data = e.Message }; } finally { stream.Close(); stream.Dispose(); } } [HttpGet] public EapResponse Getfile(string filename) { Stream stream = new MemoryStream(); try { string phyicPath = _hostingEnvironment.WebRootPath+ filename; var base64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(phyicPath)); return new EapResponse { Code = 1, Data = base64 }; } catch (Exception e) { return new EapResponse { Code = -1, Data = e.Message }; } finally { stream.Close(); stream.Dispose(); } } private void CreateDirectory(string path) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } } }