Download File on Asp net mvc

Asked

Viewed 2,136 times

1

I have files that were uploaded to wwwroot/files/ folder of my project. I want to download these files but when I click on 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},

    });
}  

1 answer

1


Nothing happens because you are trying to download via Ajax, another way to solve this would be to open a new blank window to download, for this just change its function Javascript 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 the 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);
}
  • Thanks, now you are downloading. However the file is coming empty...what could be the error in my controller? I can’t see in my Action the moment I pick up the file, I just see getting the file path.. Or this is done in the Memorystream part?

  • the Path is correct?

  • Yeah, I already checked

  • Another question, is net core?

  • That’s right!....

  • I edited with an alternative

  • 1

    It worked out! Thank you

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.