using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using Yi.Framework.Common.Enum; using Yi.Framework.Common.Models; using Yi.Framework.Interface; using Yi.Framework.WebCore; namespace Yi.Framework.ApiMicroservice.Controllers { /// /// 文件 /// [Route("api/[controller]/[action]")] [ApiController] public class FileController : ControllerBase { private IUserService _iUserService; private readonly IHostEnvironment _env; /// /// 使用本地存储,未进行数据库记录 /// /// /// public FileController(IUserService iUserService, IHostEnvironment env) { _iUserService = iUserService; _env = env; } /// /// 文件下载 /// /// /// /// [Route("/api/file/{type}/{fileName}")] [HttpGet] public IActionResult Get(string type, string fileName) { type = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(type.ToLower()); if (!Enum.IsDefined(typeof(PathEnum), type)) { return new NotFoundResult(); } try { var path = Path.Combine($"wwwroot/{type}", fileName); var stream = System.IO.File.OpenRead(path); var MimeType = Common.Helper.MimeHelper.GetMimeMapping(fileName); return new FileStreamResult(stream, MimeType); } catch { return new NotFoundResult(); } } /// /// 文件上传 /// /// /// /// [Route("/api/Upload/{type}")] [HttpPost] public async Task Upload(string type,IFormFile file) { type = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(type.ToLower()); if (!Enum.IsDefined(typeof(PathEnum), type)) { return Result.Error("上传失败!文件类型不存在!"); } try { string filename = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName); using (var stream = new FileStream(Path.Combine($"wwwroot/{type}", filename), FileMode.CreateNew, FileAccess.Write)) { await file.CopyToAsync(stream); } return Result.Success().SetData(filename); } catch { return Result.Error(); } } } }