123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- 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);
- }
- }
- }
- }
|