从服务器下载ASP.NET文件

vu8f3i0k  于 2023-03-04  发布在  .NET
关注(0)|答案(7)|浏览(156)

当用户点击一个按钮后,我想下载一个文件。我尝试了下面的方法,看起来很有效,但是没有抛出一个不可接受的异常(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();
wnavrhmk

wnavrhmk1#

您可以使用HTTP处理程序(. ashx)下载文件,如下所示:
DownloadFile.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;
        }
    }
}

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

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

代码隐藏:

protected void btnDownload_Click(object sender, EventArgs e)
{
    Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}
    • 将参数传递给HTTP处理程序:**

您只需将查询字符串变量附加到Response.Redirect(),如下所示:

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

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

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

// Use the yourVariableValue here
    • 注意**-通常将文件名作为查询字符串参数传递,以向用户建议文件的实际内容,在这种情况下,用户可以使用"另存为..."覆盖该名称值。
4si2a6ki

4si2a6ki2#

尝试使用这组代码从服务器下载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();
mccptt67

mccptt673#

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

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

这对我很有效。

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();
zujrkrfu

zujrkrfu4#

对于安德森解决方案,您可以将参数放入会话信息中,然后在response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));之后清除它们。
有关会话的详细信息,请参见MSDN页面 HttpSessionState.Add Method (String, Object)

2w3rbyxf

2w3rbyxf5#

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();

}
lskq00tm

lskq00tm6#

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

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();
        }
ycggw6v2

ycggw6v27#

在ASP.NET6.0MVCRazor上这些都不适用
控制器类中的示例添加以下内容:

using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
/// <summary>
/// Creates a download file stream for the user.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public IActionResult Download([FromQuery] string fileName)
{
    var filePath = "[...path to file...]";

    var fs = new FileStream(filePath, FileMode.Open);

    return File(fs, "application/[... content type...]", fileName);
}
}

视图.cshtml文件中的示例:

<a href="@Url.Action("Download", "Home", new { fileName = quote.fileName })">Download File</a>

相关问题