0

我有一个可以在服务器上完美打开的word文档,但是当我使用我网站的按钮单击事件下载它时,它会变得错误。我在按钮上使用下面的代码来下载文件。请帮助解决这个问题:我正在使用.net framework 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"));
4

3 回答 3

2

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

编辑
正如 Akshay Anand 所提到的,更好的方法是调用HttpContext.Current.ApplicationInstance.CompleteRequest();而不是Response.End() 查看文档。另请参阅此问题

于 2010-07-17T09:55:05.903 回答
1

而是尝试:

Response.ContentType ="application/msword";

我不使用 Word,但对于 Excel,我使用:

Response.ContentType = "application/x-msexcel"
于 2010-07-17T09:28:01.140 回答
1

好的,这是我使用的代码,它是 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 类型。祝你好运!

我将名为 MergedFile 的 pdf 文档转换为 byte(),我给它一个可以由用户输入的“ShortName”。内容长度非常重要..

于 2010-07-17T10:03:51.960 回答