Error while generating file

Asked

Viewed 245 times

0

I have a method that generates a file that method is generating the file in fact, There I have another method within my service that returns the file to the download and to that return a List until then I return this list with bytes populated to my controller as follows. Call from the 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 });
    }

referring to that call.

    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;
    }

and to call the controller I have a js with the following code

    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) {


        }
    });
};

however i n can download excel file I think I’m missing something in controller, can help me in my error ?

Thank you.

1 answer

0

Hello,

I’m not sure if it suits your situation, but to download files I use the following action in the 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");
}

I hope it somehow helps.

Browser other questions tagged

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