Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!