save to file a backend return

1

My backend controller returns a file of type xlsx to my front, this is the method that returns:

 public FileResult ListarLivrosExcel()
    {
        // Gerando minha planilha e recebendo-a
        using (ExcelPackage arquivoExcel = new BmpoDTO().Gerar())
        {
            var stream = new MemoryStream();
            arquivoExcel.SaveAs(stream);

            // Mais sobre contentType:  http://stackoverflow.com/questions/8166205/mime-type-for-excel-xml-asp-net-3-5
            string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            string fileName = "Livros.xlsx";

            stream.Position = 0;
            return File(stream, contentType, fileName);
        }
    }

Well, what I expected was that the browser would download the file in xlsx format, but it does not automatically download.

debugging I can see the return binaries:

IsitpossibletouseJStosavethesebinaries?orwouldyouforceabrowserdownloadinxlsxformat?

resultusingblob

    
asked by anonymous 20.02.2017 / 11:37

1 answer

0

In the function you are calling (eg callback of an ajax request), you can create a file from blob , associate the address with a link and download, something like:

function download(data){
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    // data são os bytes do arquivo
    // createObjectURL cria um novo objeto URL para permitir o download
    var blob =  new Blob(["\ufeff", data], {
                type: 'application/vnd.ms-excel'})
        , url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = "meu_arquivo.xlsx";
    a.click();
    window.URL.revokeObjectURL(url);
}
  

A Blob object represents an object, of the file type, with data   immutable gross. Blobs represent data that is not   JavaScript formats. The File interface is   based on Bloob, inheriting blob functionally and expanding it to   support the user's system files.

URL.createObjectURL reference.

    
20.02.2017 / 12:44