programing

서버에서 ASP.NET 파일 다운로드

batch 2023. 9. 8. 21:19
반응형

서버에서 ASP.NET 파일 다운로드

사용자가 버튼을 클릭한 후 파일을 다운로드 받기를 원합니다.효과가 있는 것처럼 보이는 다음과 같은 것을 시도해 보았지만, 허용되지 않는 예외(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();  

HTTP 핸들러(.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;
        }
    }
}

그런 다음 버튼 클릭 이벤트 핸들러에서 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");

그러면 실제 핸들러 코드에서Request에 있는 대상.HttpContext쿼리 문자열 변수 값을 가져오려면 다음과 같이 하십시오.

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

// Use the yourVariableValue here

참고 - 파일 이름을 쿼리 문자열 매개 변수로 전달하여 파일의 실제 상태를 사용자에게 제시하는 것이 일반적이며, 이 경우 다른 이름으로 저장...으로 해당 이름 값을 재정의할 수 있습니다.

서버에서 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();

다음과 같이 변경하고 서버 컨텐츠 유형에 다음과 같이 다시 배포

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

Karl Anderson 솔루션 이외에도 세션 정보에 매개 변수를 넣고 다음에 삭제할 수 있습니다.response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));.

MSDN 페이지 HttpSessionState를 참조하십시오.세션에 대한 자세한 내용을 보려면 메서드(String, Object)를 추가합니다.

ASP에서 이 중 어떤 것도 제게 적합하지 않았습니다.NET 6.0 MVC 면도기

컨트롤러 클래스 내의 예는 다음을 추가합니다.

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


}

서버에서 파일을 다운로드하는 간단한 솔루션:

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

언급URL : https://stackoverflow.com/questions/18477398/asp-net-file-download-from-server

반응형