ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • asp.net mvc File download (파일 다운로드)
    닷넷/ASP.NET MVC 2021. 2. 23. 17:36
    반응형

    asp.net mvc 사이트에서 다운로드 버튼을 누르면

    파일을 다운로드 받을 수 있게 하려면

     

    index.cshtml에서 (혹은 파일 다운로드가 존재 할 cshtml)

    <a href="~/Home/DownloadFile?filePath=엑셀_서식.xlsx" class="excel-down"><span>엑셀서식 다운로드</span></a>
    
    <!-- Home: Views Folder or Controller Name -->
    <!-- DownloadFile: Action Name -->

     

    HomeController.cs에서 (혹은 해당 액션과 연결된 Controller)

    public ActionResult DownloadFile(string filePath)
    {
        // 다운로드 되어야 할, 서버에 존재하는 파일 경로 
        string fullName = Server.MapPath("~/Files/" + filePath);
    
        byte[] fileBytes = GetFile(fullName);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, filePath);
    }
    
    byte[] GetFile(string s)
    {
        System.IO.FileStream fs = System.IO.File.OpenRead(s);
        byte[] data = new byte[fs.Length];
        int br = fs.Read(data, 0, data.Length);
        if (br != fs.Length)
            throw new System.IO.IOException(s);
        return data;
    }

     

    예제 코드와 같이 작성 후

     

    사이트에서 엑셀서식 다운로드 버튼을 누르면

     

    파일 다운로드를 할 수 있다.

     

    이때, 파일의 확장자는 거의 다 된다.

    반응형

    댓글

Designed by Tistory.