【问题标题】:Download all types of files from server using ASP.NET使用 ASP.NET 从服务器下载所有类型的文件
【发布时间】:2013-02-07 08:12:06
【问题描述】:

我在服务器中有一个文件。

我要下载这个文件。

我用这个代码

try
    {
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.BufferOutput = true;

        if (File.Exists(Server.MapPath("~/Upload/" + file)))
        {
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file);
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(("~/Upload/" + file));
            Response.End();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        else
        {
            if (Request.UrlReferrer != null)
            {
                Type csType = GetType();
                string jsScript = "alert('File Not Found');";
                ScriptManager.RegisterClientScriptBlock(Page, csType, "popup", jsScript, true);
            }
        }
    }
    catch (Exception ex)
    {
        string errorMsg = ex.Message;
        ScriptManager.RegisterClientScriptBlock(Page, GetType(), "popup", errorMsg, true);
    }

但是当我使用这个时,我得到了错误

无法评估表达式,因为代码已优化或本机框架位于调用堆栈顶部。

在代码中

Response.End();

如何下​​载所有类型的文件?

【问题讨论】:

    标签: asp.net


    【解决方案1】:

    这是 Web 窗体、MVC 还是自定义 IHttpHandler?

    在任何情况下,您都不需要调用Response.End()HttpContext.Current.ApplicationInstance.CompleteRequest(),只需从您的函数中调用return,并确保没有其他内容写入响应。

    【讨论】:

    • 非常感谢,这是一个 Web 表单。我删除了Response.End() HttpContext.Current.ApplicationInstance.CompleteRequest(),我没有收到错误但没有下载文件。
    • 你能调试你的代码吗?您能否单步执行您的代码并查看是否抛出或捕获了任何异常?考虑删除您的 try/catch 块。
    • 是的,我调试了它,但没有抛出或捕获任何异常。
    【解决方案2】:

    你试过了吗:

    Response.TransmitFile(Server.MapPath("~/Upload/" + file));
    

    而不是:

    Response.WriteFile(("~/Upload/" + file));
    

    您还应该删除 BufferOutput(不带Response.Flush()Response.End() 是个坏主意)

    【讨论】:

    • 啊,很好,我没有看到缓冲已启用。这就解释了。
    • 非常感谢,我用这个Response.TransmitFile(Server.MapPath("~/Upload/" + file)); 但不会下载。
    • @Niloo 你也应该删除 Response.BufferOutput = true;
    • 我删除它,但不要下载 :(
    猜你喜欢
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多