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

148
Visualizações
java - downloading a input stream using servlets

I am using the following code to get the content from an object in s3 bucket. I am able to copy the data into a file locally, but the file needs to be 'downloaded' and it has to be shown in the browser's downloads list. I searched a bit about this and cam to know this has something to do with response.setHeader( "Content-Disposition", "attachment;filename=\"" + filename + "\"" ); I tried to add that too but somehow couldn't get it to work. My understanding is that the source has to be a file on a server which is converted into a stream. but I get the s3 contents in the form of a input stream. How to i download this as a file in the browser? Below is the code i have tried so far

AmazonS3 s3 = new AmazonS3Client(new ProfileCredentialsProvider());    
S3Object fetchFile = s3.getObject(new GetObjectRequest(bucketname, fileloc));
        final BufferedInputStream i = new BufferedInputStream(fetchFile.getObjectContent());
        response.setContentType("application/json");
        response.setHeader( "Content-Disposition", "attachment;filename=\"" + filename + "\"" );            
        ServletOutputStream sos = response.getOutputStream();
        int bytesread = i.read();
        while(bytesread!=-1)
        {
            sos.write(bytesread);
            bytesread = i.read();
        }
        if(i!= null)i.close();
        if(sos!= null)sos.close();
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Everything is correct except the file reading part.

//Set the size of buffer to stream the data.
  byte []buffer=new byte[1024*8];

instead of

  int byte=i.read();

Now read the file.

  while( ( length = yourInputStream.read(buffer))!=-1)
    {       yourOutputStream.write(buffer); 
                }
    System.out.println("File is downloaded.");

Additionally,puting your whole code within try/catch block will help you to know the exact reason of your problem.

about 4 years ago · Santiago Trujillo Relatório
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