Подтвердить что ты не робот

Как я могу представить файл для загрузки с контроллера 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?

4b9b3361

Ответ 1

Вернуть FileResult или FileStreamResult от вашего действия, в зависимости от того, существует ли файл или вы его создаете на лету.

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

Ответ 2

Чтобы заставить загружать PDF файл, а не обрабатываться плагином браузера PDF:

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

Если вы хотите, чтобы браузер обрабатывал свое поведение по умолчанию (плагин или загрузка), просто отправьте два параметра.

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

Вам нужно будет использовать третий параметр, чтобы указать имя файла в диалоговом окне браузера.

ОБНОВЛЕНИЕ: Шарлино прав, когда передается третий параметр (имя файла загрузки) Content-Disposition: attachment; добавляется в заголовок ответа Http. Мое решение состояло в том, чтобы отправить application\force-download в качестве типа mime, но это порождает проблему с именем файла загрузки, поэтому для отправки хорошего имени файла требуется третий параметр, поэтому устранение необходимости принудительного скачивания.

Ответ 3

Вы можете сделать то же самое в Razor или в контроллере, например.

@{
    //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

Ответ 4

Вы должны посмотреть на метод File для контроллера. Это именно то, для чего это нужно. Он возвращает FilePathResult вместо ActionResult.

Ответ 5

mgnoonan,

Вы можете сделать это, чтобы вернуть 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");
    }
}

Ответ 6

Используйте тип файла .ashx и используйте тот же код