0

tenho um metodo que gera um arquivo esse metodo esta gerando o arquivo de fato, ai tenho um outro metodo dentro da minha service que retorna o arquivo para o download e para isso retorno uma List até entao eu retorno essa lista com bytes populada para minha controler da seguinte forma. Chamada da Controller

    public JsonResult RetornaDownloadExcel(Guid GuidExcel)
    {
        var retorno = 
    JsonServiceHelper.GimmeInstance().ExecuteArray("http://localhost:1234/", 
    "/SNService/RetornaDownloadExcel", GuidExcel, true);

        List<Byte> Bytes = retorno.Value.ToObject<List<Byte>>();

        var base64 = Convert.ToBase64String(Bytes.ToArray());
        var fileSrc = String.Format("data:application/vnd.ms-excel;base64,{0}", base64);

        return Json(new { Bytes });
    }

que se refere a essa chamada.

    public List<Byte> RetornaDownloadExcel(Guid GuidExcel)
    {

        List<Byte> Bytes = new List<Byte>();
        String fullpath = "C:/Relatorio/Sns/" + GuidExcel + ".xls";

        if (File.Exists(fullpath))
        {
            StreamReader sr = new StreamReader(fullpath);

            MemoryStream ms = new MemoryStream();

            sr.BaseStream.CopyTo(ms);


            foreach (var Byte in ms.ToArray())
            {
                Bytes.Add(Convert.ToByte(Byte));
            }
        }

        return Bytes;
    }

e para chamar a controller tenho um js com o seguinte código

    function RetornaDownloadExcel() {
    jQuery.ajaxSettings.traditional = true;
    $.ajax({
        type: "POST",
        url: '/SN/RetornaDownloadExcel',
        data: { GuidExcel: guidexcel },
        success: function (data) {
            a = document.createElement('a');
            document.body.appendChild(a);
            var byteArray = new Uint8Array(data.Bytes);
            blob = new Blob([byteArray], { type: 'application/vnd.ms-excel' 
    });
            url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = "Sns.xls";
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        },
        error: function (xhr, status, error) {


        }
    });
};

porem eu n consigo fazer o download do arquivo excel acho que estou errando em algo na controller, podem me ajudar no meu erro ?

Obrigado.

1 Resposta 1

0

Olá,

Não tenho certeza se atende sua situação, mas para download de arquivos utilizo a seguinte action no controller:

public FileResult DownloadFile()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(@"c:\temp\meuArquivo.xls");
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "meuArquivo.xls");
}

Espero que de alguma maneira ajude.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .