Download File in asp net mvc

1

I have files that have been uploaded to the wwwroot / files / folder of my project. I want to download these files but when I click the button nothing happens.

public ActionResult DownloadFile(string arquivo)
    {

        if (arquivo == null)
            return Content("filename not present");

        var path = Path.Combine(
                       Directory.GetCurrentDirectory(),
                       "wwwroot", "arquivos", arquivo);
        var memory = new MemoryStream();

        var writer = new StreamWriter(memory);
        writer.Flush();
        memory.Position = 0;
        return File(memory, GetContentType(path), arquivo);
    }

html

<li>Download:                     
   <a class="btn btn-primary mb-3" onclick="downloadMaterial(this)" [email protected](modelItem => item.Arquivo)><span class="glyphicon glyphicon-download-alt"></span></a>
</li>

function downloadMaterial(e){
  var path = e.name;
  var arquivo = path.split("arquivos/")[1];
    $.ajax({
      url: '@Url.Action("DownloadFile")',
      type: "POST", 
      cache: false,
      data: {'arquivo': arquivo},

    });
}  
    
asked by anonymous 10.10.2018 / 16:00

1 answer

1

Nothing happens because you are trying to download via Ajax , another way to resolve this would be by opening a new blank window for download, so just change your JavaScript in> to the following:

<li>Download:                     
   <a class="btn btn-primary mb-3" onclick="downloadMaterial(this)" [email protected](modelItem => item.Arquivo)><span class="glyphicon glyphicon-download-alt"></span></a>
</li>

<script>
    function downloadMaterial(e){
      var path = e.name;
      var arquivo = path.split("arquivos/")[1];
      window.open("/Controller/DownloadFile/?arquivo=" + arquivo, "_blank")     
    }
</script>   

For download you can do so:

public ActionResult DownloadFile(string arquivo)
{
    if (arquivo == null)
        return Content("filename not present");

    var path = Path.Combine(
                   Directory.GetCurrentDirectory(),
                   "wwwroot", "arquivos", arquivo);

    FileStream fileStream;

    try
    {
        fileStream = System.IO.File.OpenRead(path);
    }
    catch (DirectoryNotFoundException)
    {
        return new EmptyResult();
    }

    return File(fileStream, GetContentType(path), arquivo);
}
    
10.10.2018 / 16:11