asp.net core webapi 文件下载实现
在.NET Web API Core 中实现文件下载
var fileProvider = new PhysicalFileProvider("\\host\patha\pathb\");//绝对路径,如 c:\files\ ;网络路径:\\a\b\c var diretoryOptions = new DirectoryBrowserOptions { FileProvider = fileProvider, RequestPath = "/files", Formatter= new MyDirectoryFormatter(HtmlEncoder.Default)//自定义文件目录页面 }; var fileExtensionContentTypeProvider = new FileExtensionContentTypeProvider(); fileExtensionContentTypeProvider.Mappings[".xml"]= "application/octet-stream"; //IE不支持 var fileOptions = new StaticFileOptions { FileProvider = fileProvider, RequestPath = "/documents", ContentTypeProvider = fileExtensionContentTypeProvider, OnPrepareResponse = (staticFileResponseContext)=>{ staticFileResponseContext.Context.Response.Headers.Add("content-disposition", "attachment"); }//在IE中让文件作为附件下载 }; app.UseDirectoryBrowser(diretoryOptions); app.UseStaticFiles(); app.UseStaticFiles(fileOptions);
MyDirectoryFormatters 实现 IDirectoryFormatter接口,可以自定义文件夹显示界面;
DirectoryBrowserOptions 建立文件夹与URL的映射
StaticFileOptions 建立文件与URL的映射