Programing

MVC 컨트롤러에서 다운로드 할 파일을 어떻게 제시합니까?

crosscheck 2020. 8. 5. 07:48
반응형

MVC 컨트롤러에서 다운로드 할 파일을 어떻게 제시합니까?


WebForms에는 보통 브라우저가 PDF와 같은 임의의 파일 형식 및 파일 이름으로 "파일 다운로드"팝업을 표시 할 수 있도록 다음과 같은 코드가 있습니다.

Response.Clear()
Response.ClearHeaders()
''# Send the file to the output stream
Response.Buffer = True

Response.AddHeader("Content-Length", pdfData.Length.ToString())
Response.AddHeader("Content-Disposition", "attachment; filename= " & Server.HtmlEncode(filename))

''# Set the output stream to the correct content type (PDF).
Response.ContentType = "application/pdf"

''# Output the file
Response.BinaryWrite(pdfData)

''# Flushing the Response to display the serialized data
''# to the client browser.
Response.Flush()
Response.End()

ASP.NET MVC에서 동일한 작업을 어떻게 수행합니까?


파일이 존재하는지 또는 즉시 파일을 작성하는지에 따라 조치에서 FileResult또는 FileStreamResult조치에서 리턴 하십시오.

public ActionResult GetPdf(string filename)
{
    return File(filename, "application/pdf", Server.UrlEncode(filename));
}

브라우저의 PDF 플러그인에서 처리하는 대신 PDF 파일을 강제로 다운로드하려면 :

public ActionResult DownloadPDF()
{
    return File("~/Content/MyFile.pdf", "application/pdf", "MyRenamedFile.pdf");
}

브라우저가 기본 동작 (플러그인 또는 다운로드)으로 처리하도록하려면 두 개의 매개 변수 만 보내십시오.

public ActionResult DownloadPDF()
{
    return File("~/Content/MyFile.pdf", "application/pdf");
}

브라우저 대화 상자에서 파일 이름을 지정하려면 세 번째 매개 변수를 사용해야합니다.

업데이트 : Charlino는 세 번째 매개 변수 (다운로드 파일 이름) Content-Disposition: attachment;를 전달하면 HTTP 응답 헤더에 추가됩니다. 내 솔루션은 application\force-downloadMIME 유형 으로 전송 하는 것이지만 다운로드 파일 이름에 문제가 발생하므로 좋은 파일 이름을 보내려면 세 번째 매개 변수가 필요하므로 다운로드강제 할 필요가 없습니다 .


Razor 또는 Controller에서 동일한 작업을 수행 할 수 있습니다.

@{
    //do this on the top most of your View, immediately after `using` statement
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}

또는 컨트롤러에서 ..

public ActionResult Receipt() {
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");

    return View();
}

Chrome과 IE9에서 이것을 시도했는데 둘 다 pdf 파일을 다운로드하고 있습니다.

아마도 RazorPDF사용하여 PDF를 생성하고 추가해야 할 것입니다 . 여기에 블로그가 있습니다 : http://nyveldt.com/blog/post/Introducing-RazorPDF


You should look at the File method of the Controller. This is exactly what it's for. It returns a FilePathResult instead of an ActionResult.


mgnoonan,

You can do this to return a FileStream:

/// <summary>
/// Creates a new Excel spreadsheet based on a template using the NPOI library.
/// The template is changed in memory and a copy of it is sent to
/// the user computer through a file stream.
/// </summary>
/// <returns>Excel report</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult NPOICreate()
{
    try
    {
        // Opening the Excel template...
        FileStream fs =
            new FileStream(Server.MapPath(@"\Content\NPOITemplate.xls"), FileMode.Open, FileAccess.Read);

        // Getting the complete workbook...
        HSSFWorkbook templateWorkbook = new HSSFWorkbook(fs, true);

        // Getting the worksheet by its name...
        HSSFSheet sheet = templateWorkbook.GetSheet("Sheet1");

        // Getting the row... 0 is the first row.
        HSSFRow dataRow = sheet.GetRow(4);

        // Setting the value 77 at row 5 column 1
        dataRow.GetCell(0).SetCellValue(77);

        // Forcing formula recalculation...
        sheet.ForceFormulaRecalculation = true;

        MemoryStream ms = new MemoryStream();

        // Writing the workbook content to the FileStream...
        templateWorkbook.Write(ms);

        TempData["Message"] = "Excel report created successfully!";

        // Sending the server processed data back to the user computer...
        return File(ms.ToArray(), "application/vnd.ms-excel", "NPOINewFile.xls");
    }
    catch(Exception ex)
    {
        TempData["Message"] = "Oops! Something went wrong.";

        return RedirectToAction("NPOI");
    }
}

Although standard action results FileContentResult or FileStreamResult may be used for downloading files, for reusability, creating a custom action result might be the best solution.

As an example let's create a custom action result for exporting data to Excel files on the fly for download.

ExcelResult class inherits abstract ActionResult class and overrides the ExecuteResult method.

We are using FastMember package for creating DataTable from IEnumerable object and ClosedXML package for creating Excel file from the DataTable.

public class ExcelResult<T> : ActionResult
{
    private DataTable dataTable;
    private string fileName;

    public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
    {
        this.dataTable = new DataTable();
        using (var reader = ObjectReader.Create(data, columns))
        {
            dataTable.Load(reader);
        }
        this.fileName = filename;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context != null)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
            using (XLWorkbook wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dataTable, "Sheet1");
                using (MemoryStream stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    response.BinaryWrite(stream.ToArray());
                }
            }
        }
    }
}

In the Controller use the custom ExcelResult action result as follows

[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
    var model = new Models.MyDataModel();
    var items = await model.GetItems();
    string[] columns = new string[] { "Column1", "Column2", "Column3" };
    string filename = "mydata.xlsx";
    return new ExcelResult<MyViewModel>(items, filename, columns);
}

HttpGet을 사용하여 파일을 다운로드하고 있으므로 모델과 빈 레이아웃이없는 빈 뷰를 만듭니다.

즉석에서 생성 된 파일을 다운로드하기위한 사용자 지정 동작 결과에 대한 블로그 게시물 :

https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html


.ashx 파일 형식을 사용하고 동일한 코드를 사용하십시오

참고 : https://stackoverflow.com/questions/730699/how-can-i-present-a-file-for-download-from-an-mvc-controller

반응형