How to provide a friendly name to a File in ASP.NET Core without forcing the file to be downloaded?

345 Views Asked by At

I have the following REST Endpoint defined in my ASP.NET Core 3.1 application:

[HttpGet("files/{id}")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult GetFile(int id)
{
    // ...
   return File(stream, mime);
}

If I leave the code as-is, then the file is either immediately downloaded or previewed in the browser depending on whether or not the browser can preview the file (i.e. pdf file). However, when the user goes to download the file, the name of the file is the id; for example, saving the pdf will suggest to save 701.pdf. Files which cannot be previewed are immediately downloaded with that same convention.

I can supply the downloadFileName return File(stream, mime, friendlyName), but then even files which could be previewed (i.e. pdf files) are immediately downloaded. Is there a way to provide a friendly name without enforcing file download?

1

There are 1 best solutions below

0
On

Try this two workaround:

1)

View:

<a asp-action="GetFile" asp-controller="Users">Download</a>

Controller (be sure that the file have been exsit in wwwroot/file folder):

 [HttpGet]
 public ActionResult GetFile()
 {
     string filePath = "~/file/test.pdf";
     Response.Headers.Add("Content-Disposition", "inline; filename=test.pdf");
     return File(filePath, "application/pdf");           
 }

Startup.cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   //...
   app.UseStaticFiles();
   //...
}
public async Task<IActionResult> GetFile()
{
    var path = Path.Combine(
    Directory.GetCurrentDirectory(), "wwwroot\\images\\4.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");
}

View:

<form asp-controller="pdf" asp-action="GetFile" method="get">
  <button type="submit">Download</button>
</form>