【问题标题】:Output file from an .aspx page.aspx 页面的输出文件
【发布时间】:2013-08-08 20:53:35
【问题描述】:

我正在尝试使用代码隐藏 C# 代码从我的 DownloadFile.aspx 页面输出一个文件。我执行以下操作:

protected void Page_Load(object sender, EventArgs e)
{
    string strFilePath = @"C:\Server\file";
    string strFileName = @"downloaded.txt";

    long uiFileSize = new FileInfo(strFilePath).Length;

    using (Stream file = File.OpenRead(strFilePath))
    {
        Response.ContentType = "application/octet-stream";

        Response.AddHeader("Content-Disposition", "attachment; filename=\"" + strFileName + "\"");
        Response.AddHeader("Content-Length", uiFileSize.ToString());

        Response.OutputStream.CopyTo(file);

        Response.End();
    }
}

这可行,但是当文件被下载并保存时,它的内容只是一个 HTML 页面。

我在这里做错了什么?

【问题讨论】:

    标签: c# asp.net web-applications download


    【解决方案1】:

    您正在向后复制流。应该是:

    file.CopyTo(Response.OutputStream);
    

    【讨论】:

    • 另一个不用处理流的东西是Response.WriteFile(strFilePath);
    • 哈哈。惊人的!谢谢。
    【解决方案2】:

    在发送文件之前清除响应,并改用 TransmitFile 方法。

        Response.Clear()
        Response.TransmitFile("FilePath.ext")
        Response.End()
    

    http://msdn.microsoft.com/en-us/library/12s31dhy.aspx

    【讨论】:

    • +1 TransmitFileWriteFile。没注意到有两个不同的,这个更好看。
    • 谢谢。清除标题可能是个好主意 :) 我使用更长的方法的原因是因为我需要更改正在下载的文件名。
    猜你喜欢
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多