Home > OS >  How to download a PDF file using ASP.Net Core
How to download a PDF file using ASP.Net Core

Time:12-21

    public IActionResult DownloadFile()
    {
        string webRootPath = _webHostEnvironment.WebRootPath;
        string outputFilePath = Path.Combine(webRootPath, "pdf", "sample.pdf");
        var fileInfo = new System.IO.FileInfo(outputFilePath);
        Response.ContentType = "application/pdf";
        Response.Headers.Add("Content-Disposition", String.Format("attachment;filename=\"{0}\"", outputFilePath));
        Response.Headers.Add("Content-Length", fileInfo.Length.ToString());
        Response.WriteAsync(outputFilePath);
        
    }

I used this code to download a file using asp.net core. But It was not downloaded.. What is an Issue and how to download a pdf file using ASP.Net Core?

CodePudding user response:

You can try the code below:

  • Check if the file exists
  • If it doesn't, return a 404 error
  • If it does:
    • Set the Content-Type to application/pdf
    • Set the Content-Disposition to attachment
    • Set the Content-Length to the file size
    • Send the file to the client using the File method
public IActionResult DownloadFile()
{
    string webRootPath = _webHostEnvironment.WebRootPath;
    string outputFilePath = Path.Combine(webRootPath, "pdf", "sample.pdf");

    if (!System.IO.File.Exists(outputFilePath))
    {
        // Return a 404 Not Found error if the file does not exist
        return NotFound();
    }

    var fileInfo = new System.IO.FileInfo(outputFilePath);
    Response.ContentType = "application/pdf";
    Response.Headers.Add("Content-Disposition", "attachment;filename=\""   fileInfo.Name   "\"");
    Response.Headers.Add("Content-Length", fileInfo.Length.ToString());

    // Send the file to the client
    return File(System.IO.File.ReadAllBytes(outputFilePath), "application/pdf", fileInfo.Name);
}

Don't forget to inject instance of IWebHostEnvironment:

private readonly IWebHostEnvironment _webHostEnvironment;

public ChangeMeController(IWebHostEnvironment webHostEnvironment)
{
    _webHostEnvironment = webHostEnvironment;
}

CodePudding user response:

Could you try the below code:

 public async Task<IActionResult> DownloadFileAsync()
        {
            
            var path = Path.Combine(
    Directory.GetCurrentDirectory(), "wwwroot\\pdf\\sample.pdf");

            var memory = new MemoryStream();
            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            return File(memory, "application/pdf", "Demo.pdf");
        }

result: enter image description here

  • Related