-1

This is my View Code and I am using a ViewBag to get the files from controller

<ul class="list-unstyled">
  @foreach (var File in ViewBag.ProjectsFiles)
  {
  <li>
  <span class="text-secondary"> @File.FilesName <span class="btn-link text-secondary"><a  href="http://localhost:44360/Test/Index/DownloadFile?file=@File.FilesName" target="_blank" class="float-right"><i class="fas fa-download"></i></a></span></span>
  </li>
  }
  </ul>

and this is my controller method to download the files on click in link

public void DownloadFile(String file)
        {
            try
            {
                String filename = file;
                String filepath = Server.MapPath("~/Files/" + filename);

                Response.Clear();
                Response.ClearHeaders();
                Response.ClearContent();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                Response.Flush();

                Response.TransmitFile(filepath);
                Response.End();
                // HttpContext.ApplicationInstance.CompleteRequest();
                ViewBag.Message = "";
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message.ToString();
            }

        }

But the probleme when I click the file's not downloading. Any hints?

Falco Alexander
  • 3,092
  • 2
  • 20
  • 39
marco debala
  • 99
  • 1
  • 8
  • did you debug it and set a breakpoint in the controller? – Falco Alexander Jul 04 '20 at 08:31
  • @FalcoAlexander not yet – marco debala Jul 04 '20 at 08:34
  • **Warning:** You are setting yourself up for a [path traversal exploit](https://owasp.org/www-community/attacks/Path_Traversal). Pass in `../../WebApplication1.sln` to the DownloadFile function and if the file exists it will happily return it. Validate your user input for these kind of characters. – Dennis VW Jul 04 '20 at 08:44

1 Answers1

4

You can use the following code below, this will return the file when controller is called. You can find related information on this link Download file of any type in Asp.Net MVC using FileResult?

        public FileResult Download(String file)
    {
        String filepath = Server.MapPath("~/Files/" + file);
        byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file);
    }