提供Word下载接口

1. 准备Word文件并嵌入到类库中

  1. 将Word文件放入类库的DownloadTemplate文件夹

  2. 在类库项目文件(.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文件。

posted @ 2025-02-20 15:08  YangGod  阅读(21)  评论(0)    收藏  举报