Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda