using System; using System.Globalization; 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 IWebHostEnvironment _host; public FileController(IWebHostEnvironment host) { this._host = host; } public IActionResult Upload() { 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) { if (file is null) { throw new ArgumentNullException(nameof(file)); } using (Stream stream = file.OpenReadStream()) { var ext = GetExtension(file.FileName); var md5 = GetFileNameHash(stream); var phicyPath = Path.Combine(this._host.WebRootPath, "upload"); Directory.CreateDirectory(phicyPath); var name = string.Format(CultureInfo.CurrentCulture, "{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 static string GetExtension(string value) { return value.Substring(value.LastIndexOf('.') + 1).ToLower(CultureInfo.CurrentCulture); } private static string GetFileNameHash(Stream input) { using (var hashAlg = SHA256.Create()) { byte[] hash = hashAlg.ComputeHash(input); return BitConverter.ToString(hash).Replace("-", string.Empty, true, CultureInfo.CurrentCulture).ToLower(CultureInfo.CurrentCulture); } } #endregion private } }