/// <summary> /// Handle /// </summary> /// <param name="query"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <QueryResponse> Handle(DownloadQuery query, CancellationToken cancellationToken) { QueryResponse response = new QueryResponse(); Stream ms = new MemoryStream(); try { ms = await _storageService.GetFileStream(query.FilePath); ms.Position = 0; // Have to reset the current position } catch (Exception ex) { // Exception and logging are handled in a centralized place, see ApiExceptionFilter. throw new EntityNotFoundException(nameof(AttachmentModel), query.FilePath); } // Content Type mapping string[] fileNameParts = query.FilePath.Split('/', StringSplitOptions.RemoveEmptyEntries); string fileName = fileNameParts[fileNameParts.Length - 1]; var contentTypeProvider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); string contentType = "application/octet-stream"; if (!contentTypeProvider.TryGetContentType(fileName, out contentType)) { contentType = "application/octet-stream"; // fallback } response.FileName = String.IsNullOrEmpty(query.OriginalFileName) ? fileName : query.OriginalFileName; response.Stream = ms; response.ContentType = contentType; return(response); }
/// <summary> /// Attempts to intelligently guess the content mime type from the file name /// </summary> public static string ContentType(string fileName) { var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); if (!provider.TryGetContentType(fileName, out string contentType)) { contentType = "application/octet-stream"; } return(contentType); }
private string GetMimeType(string fileName) { // Make Sure Microsoft.AspNetCore.StaticFiles Nuget Package is installed var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); string contentType; if (!provider.TryGetContentType(fileName, out contentType)) { contentType = "application/octet-stream"; } return(contentType); }
/// <summary> /// Crea una respuesta de devolución de fichero /// </summary> /// <param name="file">Array de bytes del fichero</param> /// <param name="fileName">Nombre del fichero</param> /// <returns></returns> public static IActionResult CreateFileResponse(byte[] file, string fileName) { var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); string contentType; if (!provider.TryGetContentType(fileName, out contentType)) { contentType = "application/octet-stream"; } return(new FileContentResult(file, contentType) { FileDownloadName = fileName, LastModified = DateTime.Now }); }
static string GetContentType(string file) { if (file.EndsWith(".ts")) { return("text/x.typescript"); } var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); if (!provider.TryGetContentType(file, out var contentType)) { contentType = "application/octet-stream"; } return(contentType); }
public IActionResult DownloadFile(string name) { // var ffile =await _UnitOfWork.Requests.GetAsync(id); string FilePath = Path.Combine(_enviroment.WebRootPath, "image/Document") + $@"\{name}"; //string FileName = $"{name.Name}.{name.Type}"; string FileName = $"{name}"; var fileProvider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); if (!fileProvider.TryGetContentType(FilePath, out string contentType)) { throw new ArgumentOutOfRangeException($"Unable to find Content Type for file name {FilePath}."); } byte[] file = System.IO.File.ReadAllBytes(FilePath);//به بایت تبدیل کن return(File(file, contentType, fileDownloadName: FileName)); }
public static string getMimeTypeFromExtension(string extension, string failoverMime = "application/octet-stream") { bool identified; string fileName, fileMime; Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider extensionContentTypeProvider; extensionContentTypeProvider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); extensionContentTypeProvider.Mappings.Add(".exe", "application/vnd.microsoft.portable-executable"); fileName = "basename." + extension.TrimStart('.'); identified = (extensionContentTypeProvider.TryGetContentType(fileName, out fileMime)); if (identified) { return(fileMime); } else { return(failoverMime); } }
public IActionResult GetImage(string id, string temp, string temp1) { if (string.IsNullOrWhiteSpace(id)) { return(null); } var file = System.IO.Path.Combine(_destination, id); var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); string contentType; if (!provider.TryGetContentType(file, out contentType)) { contentType = "application/octet-stream"; } if (System.IO.File.Exists(file)) { return(File(new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read), contentType)); } return(null); }
public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env, ILoggerFactory loggerFactory, Microsoft.AspNetCore.Hosting.IApplicationLifetime lifetime) { var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider(); // Add new mappings provider.Mappings[".ps1"] = "text/plain"; provider.Mappings[".psm1"] = "text/plain"; provider.Mappings[".psd1"] = "text/plain"; provider.Mappings[".log"] = "text/plain"; provider.Mappings[".yml"] = "text/plain"; app.UseResponseCompression(); app.UseStatusCodePages(async context => { if (context.HttpContext.Response.StatusCode == 404 && !context.HttpContext.Request.Path.StartsWithSegments("/api")) { var fileName = context.HttpContext.Request.Path.ToString().Split('/').Last(); var asset = AssetService.Instance.FindAsset(fileName); if (asset != null) { var response = context.HttpContext.Response; if (provider.TryGetContentType(asset, out string mimeType)) { response.ContentType = mimeType; } response.StatusCode = 200; var file = File.ReadAllBytes(asset); await response.Body.WriteAsync(file, 0, file.Length); } else { var response = context.HttpContext.Response; response.StatusCode = 200; var filePath = env.ContentRootPath + "/index.html"; response.ContentType = "text/html; charset=utf-8"; var file = File.ReadAllText(filePath); await response.WriteAsync(file); } } else { await context.Next(context.HttpContext); } }); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(env.ContentRootPath), RequestPath = new PathString(""), ServeUnknownFileTypes = true, ContentTypeProvider = provider }); ConfigureActions.ForEach(x => x(app, env, loggerFactory, lifetime)); var dashboardService = app.ApplicationServices.GetService(typeof(IDashboardService)) as IDashboardService; if (dashboardService?.DashboardOptions?.Certificate != null || dashboardService?.DashboardOptions?.CertificateFile != null) { if (dashboardService.DashboardOptions.Port == dashboardService.DashboardOptions.HttpsPort) { Logger.Warn("Port and HTTPS port are the same. HTTPS Redirection will not work. Select two different ports."); } else { app.UseHttpsRedirection(); } } if (dashboardService?.DashboardOptions?.PublishedFolders != null) { foreach (var publishedFolder in dashboardService.DashboardOptions.PublishedFolders) { app.UseStaticFiles(new StaticFileOptions { RequestPath = publishedFolder.RequestPath, FileProvider = new PhysicalFileProvider(publishedFolder.Path), ServeUnknownFileTypes = true, ContentTypeProvider = provider }); } } app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials()); app.UseSignalR(routes => { routes.MapHub <DashboardHub>("/dashboardhub"); }); app.UseWebSockets(); app.UseSession(); app.UseMvc(); }