How to start a download automatically when the user enters a specific page

Asked

Viewed 32 times

-1

I have a MVC C#application, where after login (it will be the first time you access the platform) the system starts downloading some files (the files change according to the needs of the department, in the same way that can increase the number of files or decrease).

I already had a code that generated the dynamic download, however, I do not know how to make it automatic.

public ActionResult Download(string nome, string cpf)
    {
        try
        {
            string contentType = "";
            var arquivos = ListaArquivos();
            string nomeArquivo = (from arquivo in arquivos
                                  where arquivo.Nome == nome
                                  select arquivo.Caminho).First();
            string extensao = Path.GetExtension(nomeArquivo);
            string nomeArquivoV = Path.GetFileNameWithoutExtension(nomeArquivo);
            if (extensao.Equals(".pdf"))
                contentType = "application/pdf";
            if (extensao.Equals(".jpg") || extensao.Equals(".gif") || extensao.Equals(".png")) contentType = "application/image";
            if (extensao.Equals(".txt")) contentType = "text/plain";
            if (extensao.Equals(".docx")) contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            if (extensao.Equals(".doc")) contentType = "application/msword";
            File(nomeArquivo, contentType, nomeArquivoV + extensao);
        }
        catch (Exception ex)
        {
            TempData["ErrorMessage"] = true;
            TempData["Message"] = $"Não é possível realizar o download do Anexo! - {ex.ToString()}";
            return RedirectToAction("Formulario", new { cpf = cpf });
        }
    }

    private List<UploadFileResultVM> ListaArquivos()
    {
        List<UploadFileResultVM> lstArquivos = new List<UploadFileResultVM>();
        DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath(_localUpload));

        foreach (var item in dirInfo.GetFiles())
        {
            lstArquivos.Add(new UploadFileResultVM()
            {
                Nome = item.Name,
                Caminho = dirInfo.FullName + @"\" + item.Name
            });
        }
        return lstArquivos;
    }

And again, I’m doing it this way because there is no standard for the files to be downloaded, the amount varies, each area has a pattern. The differentiation of the areas already know how to solve, the problem is the automatic start of the download when the user access the page.

1 answer

0

You need to return the file:

return File(nomeArquivo, contentType, nomeArquivoV + extensao);

Browser other questions tagged

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