save in file a return from backend

Asked

Viewed 658 times

1

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

 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 the xlsx format, however the download does not occur automatically.

debugging I can see the binaries of the return : inserir a descrição da imagem aqui

Is it possible to use JS to save these binaries ? or would have to force a browser download in xlsx format?

result using the blob inserir a descrição da imagem aqui

1 answer

0

In the function you are calling (e.g., callback of an ajax request), you can create a file from blob, associate the address to 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);
}

Blob Object represents an object, file type, with data immutable brutes. Blobs represent data that is not necessarily in standard Javascript formats. The File interface is based on Bloob, inheriting block functionally and expanding it to support user system files.

Reference of URL.createObjectURL.

  • saved, however when opening the file, shows the binaries, edited the post and put a photo.

Browser other questions tagged

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