How to download A pdf file in MVC 5 directly

1

I wish that when carrying out certain operations the file generated in pdf is downloaded directly and not displayed in the browser (chrome)

    byte[] fileBytes =  System.IO.File.ReadAllBytes(@"\svr\dllo\Pendientes\" + nombrePDF);
   return File(fileBytes, "application/pdf");

In Explorer it does download directly

    
asked by ger 12.12.2016 в 15:16
source

3 answers

2

This I put together a few years ago but it can help you.

        byte[] fileBytes =  System.IO.File.ReadAllBytes(@"\svr\dllo\Pendientes\" + nombrePDF);
        MemoryStream ms = new MemoryStream(fileBytes, 0, 0, true, true);
        Response.AddHeader("content-disposition", "attachment;filename= NombreArchivo");
        Response.Buffer = true;
        Response.Clear();
        Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
        Response.OutputStream.Flush();
        Response.End();
        return new FileStreamResult(Response.OutputStream, "application/pdf");

The secret is in this line: Response.AddHeader("content-disposition", "attachment;

The browser should download it as an attachment and not open it directly.

    
answered by 12.12.2016 / 15:31
source
2

To force the download you must indicate the Content-Disposition

Response.AppendHeader("Content-Disposition", "attachment; filename=FileName.pdf");

Force Download Pdf File in C # (Asp.Net Mvc 4)

As you'll see, it varies a bit if it's an action in a webapi controller

    
answered by 12.12.2016 в 15:39
0

I use this code.

using System.Web.Mvc;

public ActionResult DamePdf(LDModel ld, string returnUrl)
{
  string contentType = System.Net.Mime.MediaTypeNames.Application.Pdf;
  return new FilePathResult(ld.fullPathfileName, contentType)
  //{ 
  //    FileDownloadName = ld.FileName,
  //};
}

The action, instead of returning a view, will return a file. if the last 3 lines are uncommented, when the file arrives it will be saved directly in the browser's download folder with the name that we put it. If so, the name should end in .pdf

Having a name, it depends on the explorer, the behavior may be different. Some keep it without asking, others show it without asking and others ask in any case. When it does not have a name, some explorers, the good ones, open it directly.

If you change the line where contentType is defined by:

string contentType = System.Net.Mime.MediaTypeNames.Application.Octet;

Specifically Crhome saves it directly without asking anything.

    
answered by 13.12.2016 в 21:10