using System; using System.IO; using System.IO.Compression; using System.Security.Cryptography; using Infrastructure.Extensions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Infrastructure.Web.Mvc { public class FileController : Controller { private readonly IHostingEnvironment _host; public FileController(IHostingEnvironment host) { this._host = host; } public IActionResult Upload(string redirectUrl) { if (Request.Form.Files != null && Request.Form.Files.Count > 0) { var file = Request.Form.Files[0]; var path = this.Save(file); return Content(new { error = 0, url = path }.ToJson()); } return Content(new { error = 1, msg = "未选择文件" }.ToJson()); } public IActionResult Json(string value) { return Content(value); } public string Save(IFormFile file) { using (Stream stream = file.OpenReadStream()) { var ext = this.GetExtension(file.FileName); var md5 = this.Md5(stream); var phicyPath = Path.Combine(this._host.WebRootPath, "upload"); Directory.CreateDirectory(phicyPath); var name = string.Format("{0}.{1}", md5, ext); var fullName = Path.Combine(phicyPath, name); if (!System.IO.File.Exists(fullName)) { using (FileStream fs = System.IO.File.Create(fullName)) { file.CopyTo(fs); } if (ext == "zip") { var zipDirectory = Path.Combine(phicyPath, md5); Directory.CreateDirectory(Path.Combine(phicyPath, md5)); ZipFile.ExtractToDirectory(fullName, zipDirectory); } } return $"/upload/{name}"; } } #region private private string GetExtension(string value) { return value.Substring(value.LastIndexOf('.') + 1).ToLower(); } private string Md5(Stream input) { using (MD5 md5 = MD5.Create()) { byte[] hash = md5.ComputeHash(input); return BitConverter.ToString(hash).Replace("-", string.Empty).ToLower(); } } #endregion private } }