You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC上传文件转PDF时Documents.Open方法参数填写问题

问题根因

你使用的Microsoft.Office.Interop.Word组件的Documents.Open()方法不接受Stream类型参数,仅支持传入本地文件的绝对路径字符串。你当前传入的uploadedFile是IFormFile打开的可读流,类型完全不匹配,所以无法正常运行。


解决方法

你需要调整2处逻辑:

  1. 调整执行顺序:先把上传的文件写入本地磁盘,再调用Word组件读取已经存好的本地文件
  2. 将Documents.Open()的参数替换为你提前拼接好的本地文件绝对路径filePath

以下是修改后的核心代码:

[HttpPost]
public IActionResult Index1(IFormFile[] files)
{
    // 遍历所有上传文件
    foreach (var file in files)
    {
        // 过滤非Word文件,避免转换报错
        var ext = Path.GetExtension(file.FileName).ToLower();
        if (ext != ".doc" && ext != ".docx")
        {
            continue;
        }
        
        // 从浏览器端获取文件名
        var fileName = System.IO.Path.GetFileName(file.FileName);

        // 拼接得到文件上传存储路径
        var filePath = Path.Combine(Directory.GetCurrentDirectory(), "upload", fileName);

        // 检查是否存在同名文件,若存在则删除
        if (System.IO.File.Exists(filePath))
        {
            System.IO.File.Delete(filePath);
        }

        // 第一步:先把上传的文件写入本地磁盘
        using (var localFile = System.IO.File.OpenWrite(filePath))
        using (var uploadedFile = file.OpenReadStream())
        {
            uploadedFile.CopyTo(localFile);
        }
        
        // 第二步:读取本地已存好的Word文件转PDF
        var appWord = new Application();
        if (appWord.Documents != null)
        {
            // 直接传本地文件的绝对路径即可
            var wordDocument = appWord.Documents.Open(filePath);
            // 拼接PDF的保存路径,存到upload目录避免丢失
            string pdfFileName = Path.GetFileNameWithoutExtension(fileName) + ".pdf";
            string pdfFilePath = Path.Combine(Directory.GetCurrentDirectory(), "upload", pdfFileName);
            if (wordDocument != null)
            {
                wordDocument.ExportAsFixedFormat(pdfFilePath, WdExportFormat.wdExportFormatPDF);
                wordDocument.Close();
            }
            appWord.Quit();
        }
    }
    ViewBag.Message = "文件上传成功";

    // 从服务器获取文件
    var model = new FilesViewModel();
    foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
    {
        model.Files.Add(
            new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
    }
    return View(model);
}

额外注意事项

  • Office Interop依赖服务器安装对应版本的Office,且服务端权限配置容易出错,生产环境更推荐用FreeSpire.Doc这类无Office依赖的NuGet包做转换
  • 要确保Word实例正常调用Quit()退出,否则会残留大量WINWORD后台进程占用服务器资源
  • Linux部署环境无法使用Office Interop,必须更换跨平台的转换组件

内容的提问来源于stack exchange,提问作者RaresHoriaPanait

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 15:24:03