public static async Task DownloadFileAsync(HttpContext ctx, StorfilerMethodOptions method, StorfilerOptions options) { string filePath = null; if (!string.IsNullOrEmpty(method.Query) && ctx.Request.Query.ContainsKey(method.Query)) { filePath = ctx.Request.Query[method.Query]; } else { filePath = ctx.GetRouteValue("fileName")?.ToString(); if (string.IsNullOrEmpty(filePath)) { Log.Warning("Could not find file in route or query", filePath); ctx.Response.StatusCode = StatusCodes.Status400BadRequest; return; } } if (!method.IsFullPath) { filePath = Path.Combine(options.DiskPaths.Read.First(), filePath); } Log.Information("Query: Read file {file}", filePath); if (!File.Exists(filePath)) { ctx.Response.StatusCode = StatusCodes.Status404NotFound; Log.Warning("File {file} does not exist", filePath); return; } using (FileStream fileStream = File.OpenRead(filePath)) { string contentType = MimeTypeMap.List.MimeTypeMap.GetMimeType(Path.GetExtension(filePath)).First(); ctx.Response.Headers.TryAdd("Content-Disposition", $"attachment; filename=\"{Path.GetFileName(filePath)}\""); ctx.Response.ContentType = contentType; await fileStream.CopyToAsync(ctx.Response.Body); } }
public static async Task SearchFilesAsync(HttpContext ctx, StorfilerMethodOptions method, StorfilerOptions options) { string fileName = ctx.GetRouteValue("fileName").ToString(); string pattern = string.IsNullOrEmpty(method.Pattern) ? fileName : method.Pattern.Replace("{fileName}", fileName); Log.Information("Query: Search files in directory {directory} with pattern {pattern}", options.DiskPaths.Read.First(), pattern); IEnumerable <string> searchFiles = Directory.EnumerateFiles(options.DiskPaths.Read.First(), pattern, SearchOption.AllDirectories); List <FileMetadatas> filesMetadatas = new List <FileMetadatas>(); foreach (string file in searchFiles) { string name = Path.GetFileName(file); string nameWithoutExt = name.Remove(name.LastIndexOf(".", StringComparison.InvariantCultureIgnoreCase)); string parent = Path.GetFileName(Path.GetDirectoryName(file)); filesMetadatas.Add(new FileMetadatas { FullPath = file, Name = name, Parent = parent, NameWithoutExt = nameWithoutExt }); } await ctx.WriteJsonAsync(filesMetadatas); }