【问题标题】:Download a DOCX file using ASP.net WEB FORM使用 ASP.net WEB FORM 下载 DOCX 文件
【发布时间】:2017-09-21 16:08:28
【问题描述】:

我有这个下载功能:

    protected void ExportData(string fileName, string fileType, string path)
    {
        System.IO.StreamReader sr = new System.IO.StreamReader(path);


        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
        Response.Charset = "";
        Response.ContentType = fileType;
        Response.Output.Write(sr.ReadToEnd());
        Response.Flush();
        Response.End();

    }

我用它:

    ExportData("infoMandat_" + g.NO_MANDAT + ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", g.URL_infoMandat);

但文件始终为空或已损坏...

可能是因为我用普通的StreamReader阅读它

答案中提出的解决方案是函数.Transmit(),标记为重复的问题绝对不是这个问题的解决方案。

【问题讨论】:

  • path 的值是多少?它是和这段代码在同一台机器上还是在其他地方?
  • 读取 DOCX 文件时是否出现异常错误?如果是,异常错误的消息文本是什么?
  • URL_infoMandat的值是多少?
  • @Equalsk 路径将指向另一台服务器,但现在,在我的 c:\

标签: c# asp.net webforms


【解决方案1】:

如果文件已经在网站文件夹中,则无需使用Stream。您可以使用TransmitFileWriteFile

请确保path 是正确的文件夹位置。例如C:\inetpub\wwwroot\samplewebsite\

protected void ExportData(string fileName, string fileType, string path)
{
    Response.ContentType = fileType;
    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
    Response.TransmitFile(Path.Combine(path + fileName));
    Response.End();
}

// Usage
ExportData("infoMandat_" + g.NO_MANDAT + ".docx", 
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document", 
    g.URL_infoMandat);

【讨论】:

  • TransmitFile() 是我一直在寻找的东西,当它是纯文本时,我使用了 .Output.Write(),DOCX 文件不是纯文本......当然。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2014-09-24
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-12
  • 2014-07-27
相关资源
最近更新 更多