提供Word下载接口
1. 准备Word文件并嵌入到类库中
-
将Word文件放入类库的
DownloadTemplate
文件夹。 -
在类库项目文件(.csproj)中配置嵌入资源:
<ItemGroup> <EmbeddedResource Include="DownloadTemplate\*.docx" /> </ItemGroup>
2. 创建Web API接口
[ApiController] [Route("api/[controller]")] public class TemplatesController : ControllerBase { private const string NamespacePrefix = "YourClassLibraryNamespace.DownloadTemplate."; // 辅助方法:处理文件下载 private IActionResult DownloadTemplate(string fileName) { var assembly = Assembly.GetAssembly(typeof(YourClassInClassLibrary)); var resourceName = NamespacePrefix + fileName; var stream = assembly.GetManifestResourceStream(resourceName); if (stream == null) { return NotFound($"文件 {fileName} 不存在"); } return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", fileName); } // 具体接口 [HttpGet("template1")] public IActionResult DownloadTemplate1() => DownloadTemplate("Template1.docx"); [HttpGet("template2")] public IActionResult DownloadTemplate2() => DownloadTemplate("Template2.docx");
3. 配置说明
-
替换命名空间:将
YourClassLibraryNamespace
替换为类库的实际命名空间。 -
添加类引用:
YourClassInClassLibrary
替换为类库中的任意类,用于获取正确的程序集。 -
-
4. 前端调用示例
5. 关键点解释
-
嵌入资源:将Word文件作为嵌入资源确保文件随程序集一起发布。
-
资源名称:资源名称由命名空间和文件夹路径组成,需确保正确拼接。
-
MIME类型:使用正确的MIME类型
application/vnd.openxmlformats-officedocument.wordprocessingml.document
使浏览器识别Word文件。
-