C# 从服务器下载 ASP.NET 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18477398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:19:35  来源:igfitidea点击:

ASP.NET file download from server

c#asp.net

提问by James Stevenson

After a user clicks a button, I want a file to be downloaded. I've tried the following which seems to work, but not without throwing an exception (ThreadAbort) which is not acceptable.

用户单击按钮后,我想要下载一个文件。我尝试了以下似乎有效的方法,但并非没有抛出不可接受的异常(ThreadAbort)。

    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "text/plain";
    response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
    response.TransmitFile(Server.MapPath("FileDownload.csv"));
    response.Flush();
    response.End();  

采纳答案by Karl Anderson

You can use an HTTP Handler (.ashx) to download a file, like this:

您可以使用 HTTP 处理程序 (.ashx) 下载文件,如下所示:

DownloadFile.ashx:

下载文件.ashx:

public class DownloadFile : IHttpHandler 
{
    public void ProcessRequest(HttpContext context)
    {   
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/plain";
        response.AddHeader("Content-Disposition", 
                           "attachment; filename=" + fileName + ";");
        response.TransmitFile(Server.MapPath("FileDownload.csv"));
        response.Flush();    
        response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Then you can call the HTTP Handler from the button click event handler, like this:

然后您可以从按钮单击事件处理程序调用 HTTP 处理程序,如下所示:

Markup:

标记:

<asp:Button ID="btnDownload" runat="server" Text="Download File" 
            OnClick="btnDownload_Click"/>

Code-Behind:

代码隐藏:

protected void btnDownload_Click(object sender, EventArgs e)
{
    Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}


Passing a parameter to the HTTP Handler:

将参数传递给 HTTP 处理程序:

You can simply append a query string variable to the Response.Redirect(), like this:

您可以简单地将查询字符串变量附加到Response.Redirect(),如下所示:

Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");

Then in the actual handler code you can use the Requestobject in the HttpContextto grab the query string variable value, like this:

然后在实际的处理程序代码中,您可以使用 中的Request对象HttpContext来获取查询字符串变量值,如下所示:

System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];

// Use the yourVariableValue here

Note- it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...

注意- 通常将文件名作为查询字符串参数传递给用户,以向用户建议文件的实际内容,在这种情况下,他们可以使用另存为...

回答by Robin Joseph

Try this set of code to download a CSV file from the server.

试试这组代码从服务器下载一个 CSV 文件。

byte[] Content= File.ReadAllBytes(FilePath); //missing ;
Response.ContentType = "text/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".csv");
Response.BufferOutput = true;
Response.OutputStream.Write(Content, 0, Content.Length);
Response.End();

回答by Robin Joseph

Further to Karl Anderson solution, you could put your parameters into session information and then clear them after response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));.

对于 Karl Anderson 解决方案,您可以将参数放入会话信息中,然后在response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));.

See MSDN page HttpSessionState.Add Method (String,?Object)for more information on sessions.

有关会话的更多信息请参阅 MSDN 页面HttpSessionState.Add Method (String,?Object)

回答by trifolius

protected void DescargarArchivo(string strRuta, string strFile)
{
    FileInfo ObjArchivo = new System.IO.FileInfo(strRuta);
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile);
    Response.AddHeader("Content-Length", ObjArchivo.Length.ToString());
    Response.ContentType = "application/pdf";
    Response.WriteFile(ObjArchivo.FullName);
    Response.End();


}

回答by AMIT KUMAR SHARMA

Making changes as below and redeploying on server content type as

进行如下更改并将服务器内容类型重新部署为

Response.ContentType = "application/octet-stream";

This worked for me.

这对我有用。

Response.Clear(); 
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); 
Response.AddHeader("Content-Length", file.Length.ToString()); 
Response.ContentType = "application/octet-stream"; 
Response.WriteFile(file.FullName); 
Response.End();

回答by Durgesh Pandey

Simple solution for downloading a file from the server:

从服务器下载文件的简单解决方案:

protected void btnDownload_Click(object sender, EventArgs e)
        {
            string FileName = "Durgesh.jpg"; // It's a file name displayed on downloaded file on client side.

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "image/jpeg";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(Server.MapPath("~/File/001.jpg"));
            response.Flush();
            response.End();
        }