using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Minio; using System; using System.Globalization; using System.IO; using System.Security.Cryptography; namespace MinIOAspNetMvcTest.Controllers { public class HomeController : Controller { private readonly ILogger _logger; private readonly IConfiguration _cfg; public HomeController(ILogger logger, IConfiguration cfg) { _logger = logger; this._cfg = cfg; } public IActionResult Index() { return View(); } [HttpPost] public IActionResult Upload() { if (Request.Form.Files != null && Request.Form.Files.Count > 0) { var file = Request.Form.Files[0]; using Stream stream = file.OpenReadStream(); var ext = GetExtension(file.FileName); var md5 = GetFileNameHash(stream); var name = $"{md5}.{ext}"; var endpoint = this._cfg["minio:endpoint"];//"play.min.io"; var accessKey = this._cfg["minio:accessKey"]; //"Q3AM3UQ867SPQQA43P2F"; var secretKey = this._cfg["minio:secretKey"]; //"zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"; var bucketName = "upload"; try { var minio = new MinioClient(endpoint, accessKey, secretKey);//.WithSSL(); bool found = minio.BucketExistsAsync(bucketName).Result; if (found) { minio.PutObjectAsync(bucketName, name, stream, stream.Length); var path = $"/upload/{name}"; return Json(new { error = 0, url = path }); } else { //minio.MakeBucketAsync(bucketName); return Json(new { error = 2, msg = $"can not found bucket {bucketName}" }); } } catch (Exception ex) { this._logger.LogError(ex.ToString()); return Json(new { error = 3, msg = ex.Message }); } } return Json(new { error = 1, msg = "未选中文件" }); } 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); } } }