我有一个Word文档,它可以在服务器上完美打开,但是当我使用我网站的按钮单击事件下载它时,它就会崩溃。我正在使用下面的代码单击按钮来下载文档。请帮助解决这个问题:我正在使用.net框架3.5

 Response.Clear();
 Response.AddHeader("Content-Disposition", "attachment; filename=StandardLetter" + _responseId.ToString() + ".doc");
 Response.ContentType = "application/octet-stream";

 Response.TransmitFile (Server.MapPath("~/document/letter/StandardLetter" + _responseId.ToString() + ".doc"));
有帮助吗?

解决方案

好的,这里是我使用的代码,它是vb但很容易转换;)

 Response.ContentType = "application/pdf"
        Dim byteArray As Byte() = File.ReadAllBytes(MergedFile)

        Response.AddHeader("Content-Disposition", "attachment;filename=""" & ShortFilename & """")
        Response.AddHeader("Content-Length", byteArray.Length)
        Response.BinaryWrite(byteArray)
        Response.Flush()
        Response.End()
.

这适用于PDF,通过更改.ContentType来Excel吐出来。所以我假设这将采用任何MIME类型。祝你好运!

我拍摄我的pdf文档名为mergedfile并将它转换为byte(),我给它一个可以由用户输入的'shortname'。内容长度非常重要..

其他提示

你有没有 Response.End() 在你发布的代码之后?如果没有,您将从添加到传输文件的 aspx 文件中获得额外的“html”代码 - 从而损坏它。

编辑
正如 Akshay Anand 提到的,更好的方法是致电 HttpContext.Current.ApplicationInstance.CompleteRequest(); 代替 Response.End() 请参阅文档. 。也可以看看 这个问题.

而是尝试:

Response.ContentType ="application/msword";
.

我不使用单词,但是对于Excel我使用:

Response.ContentType = "application/x-msexcel"
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top