public async Task <IActionResult> DownloadAsync([Required] string fileToken, [Required] string handler, string modifier) { if (!DecodeAndCheckFileToken(fileToken, out FileToken fToken, out DataResult <object> errResult)) { return(StatusCode(401, errResult.ErrorMsg)); } var rawPath = _storageSvce.GetRawFilePath(fToken.PseudoId, fToken.FileCreateTime, fToken.FileId); if (System.IO.File.Exists(rawPath)) { //如果原文件存在,并且包含缓存头则认为是未修改 //因为文件只会删除,不会修改 var reqHeaders = Request.GetTypedHeaders(); if (reqHeaders.IfNoneMatch?.Any() == true) { return(StatusCode(304)); } } else { return(NotFound("您访问的文件不存在或已被删除啦")); } try { var fileHandler = _fileHandlerMgr.GetFileHandlerByName(handler); if (fileHandler == null) { return(StatusCode(400, handler + " 不存在")); } //返回文件 var rawMime = _mimeProvider.GetMimeById(fToken.MimeId); var hCtx = new FileHandleContext() { SourcePath = rawPath, SourceMime = rawMime, Modifier = modifier, FileToken = fToken }; var result = await fileHandler.HandleAsync(hCtx); //添加缓存头 var rspHeaders = Response.GetTypedHeaders(); rspHeaders.ETag = new EntityTagHeaderValue($"\"{fToken.PseudoId}\"", true); rspHeaders.CacheControl = new CacheControlHeaderValue() { MaxAge = TimeSpan.FromDays(365) }; rspHeaders.Expires = DateTime.UtcNow.AddYears(1); return(result); } catch (Exception ex) { Logger.LogError(nameof(DownloadAsync), ex.ToString()); return(StatusCode(500, ex.Message)); } }
public async Task <IActionResult> HandleAsync(FileHandleContext context) { if (string.IsNullOrEmpty(context.Modifier)) { throw new ArgumentNullException(nameof(context.Modifier)); } var imgMod = ParseModifier(context.Modifier, context.SourceMime); if (ShouldRsponseRaw(imgMod, context)) { return(new PhysicalFileResult(context.SourcePath, context.SourceMime.ContentType)); } //判断是否有缓存 var rawDirPath = Path.GetDirectoryName(context.SourcePath); var dstFilePath = Path.Combine(rawDirPath, $"image_{imgMod.Size.Name}_{imgMod.Mime.ExtensionNames.First()}"); if (!File.Exists(dstFilePath)) { await _imgCvter.ConvertAsync(context.SourcePath, context.SourceMime, dstFilePath, imgMod); } return(new PhysicalFileResult(dstFilePath, imgMod.Mime.ContentType)); }
/// <summary> /// 是否应该返回源文件 /// </summary> private bool ShouldRsponseRaw(ImageModifier imgMod, FileHandleContext context) { if (imgMod.Mime == context.SourceMime) { if (imgMod.Size == ImageSize.Raw) { return(true); } } return(false); }
public async Task <IActionResult> HandleAsync(FileHandleContext context) { if (!System.IO.File.Exists(context.SourcePath)) { return(new NotFoundResult()); } string fileName = null; if (_options.CurrentValue.QueryFileName) { fileName = await FileRepository.GetFileNameByIdAsync(context.FileToken.PseudoId, context.FileToken.FileOwnerId); } return(new PhysicalFileResult(context.SourcePath, context.SourceMime.ContentType) { FileDownloadName = fileName }); }