1

I have one image file which i am converting to byte[] and saving it in database while user click on file link from UI that file has to be downloaded to download i have written one method

public void downloadDeclarationForm(HttpServletRequest request, 
                                      HttpServletResponse response) throws IOException {
    int payrollId = RequestUtils.getBrowsePayroll(request);
    Payroll payroll = itConfigManager.getObjectOrNull(Payroll.class, payrollId);
    int year = payrollManager.getYear(payroll.getFromDate());
    int id = NumberUtils.toInt(request.getParameter("id"));
    try {
        byte[] byteBuf = itConfigManager.getDeclarationFormBytes(id, year);
        ControllerUtils.writeFileUploadHeaders(response, 
                                 itConfigManager.getFileName(id, year), byteBuf.length);
        //response.setContentType("image/jpeg");
        OutputStream stream = new ByteArrayOutputStream();

        response.getOutputStream().write(byteBuf);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (Exception e) {
        e.printStackTrace();
        response.getOutputStream().print(
                "Error while fetching attachment..");
    } finally {
        response.getOutputStream().close();

    }

}

While i am clicking on the download link it opening the download window even in that window file name is coming correct with correct extension but its not opening the file if i am saving that file to disk and try to open its not opening can any one help me ?

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
Deepak Kumar
  • 3,623
  • 9
  • 32
  • 32

3 Answers3

2

You have to set response header - Content-Type, Conent-Length, and Content-Disposition.

For instance,

 response.setContentType("application octet-stream");
 response.setHeader("Content-Length",String.valueOf(byteBuf.length));
 response.setHeader("Content-Disposition", "attachment; filename=sample.png");
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
2

setContentType should be uncommented and parameter should be proper. For example type is 'gif' it should be response.setContentType("image/gif");. You need to make sure you have correct image type set there.

If you are not sure what file type you are getting, you can use ImageIO class. Here is discussion regarding ImageIO. How to use ImageIO to get image type and image byte array

Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167
0

Here is an example similar to your requirement. It reads an image from database and the browser can download it.

http://www.roseindia.net/jsp/downloadimage.shtml

Pragalathan M
  • 1,673
  • 1
  • 14
  • 19