Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

673
Visualizações
How do I return a byte array as response using spring boot and ajax?

I am trying to create a page that will download a file from a data stream. I am able to get the byte stream and I want to return this to client side to save it as file.

I tried the code below however, the file that is being saved is corrupted. The download process also is too quick that I think it is not downloading properly..

Java code:

@RequestMapping(value = /download, method=RequestMethod.POST)
public ResponseEntity<ByteArrayResource> download() {
        byte b[] = <retrieving byte data array here>;
        ByteArrayResource resource = new ByteArrayResource(b);
        
        ResponseEntity<ByteArrayResource> r = ResponseEntity.ok()
                .header("Content-type", "application/octet-stream")
                .header("Content-disposition", "attachment; filename=\"test.mp4\"")
                .contentLength(resource.contentLength())
                .body(resource);

    return r;
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    return null;

}

Javascript code:

$('#download').click(function() {
$.ajax({
  type: "POST",
  url: "/download",
  data: {}
}).done(function(data) {
  var a = document.createElement("a");
  document.body.appendChild(a);
  a.style = "display: none";

  var blob = new Blob([data], {type: "octet/stream"});
  var url = window.URL.createObjectURL(blob);
  a.href = url;
  a.download = "test.mp4";
  a.click();
}
}).fail(function(data) {
});
});

Hope you guys could help me.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda