Search code examples
javajakarta-eeservletshttpresponseoutputstream

How can I put a downloadable file into the HttpServletResponse?


I have the following problem: I have an HttpServlet that create a file and return it to the user that have to receive it as a download

byte[] byteArray = allegato.getFile();

InputStream is = new ByteArrayInputStream(byteArray);
Base64InputStream base64InputStream = new Base64InputStream(is);

int chunk = 1024;
byte[] buffer = new byte[chunk];
int bytesRead = -1;

OutputStream out = new ByteArrayOutputStream();

while ((bytesRead = base64InputStream.read(buffer)) != -1) {
    out.write(buffer, 0, bytesRead);
}

As you can see I have a byteArray object that is an array of bytes (byte[] byteArray) and I convert it into a file in this way:

  1. First I convert it into an InputStream object.

  2. Then I convert the InputStream object into a Base64InputStream.

  3. Finally I write this Base64InputStream on a ByteArrayOutputStream object (the OutputStream out object).

I think that up to here it should be ok (is it ok or am I missing something in the file creation?)

Now my servlet have to return this file as a dowload (so the user have to receive the download into the browser).

So what have I to do to obtain this behavior? I think that I have to put this OutputStream object into the Servlet response, something like:

ServletOutputStream stream = res.getOutputStream();

But I have no idea about how exactly do it? Have I also to set a specific MIME type for the file?


Solution

  • It's pretty easy to do.

    byte[] byteArray = //your byte array
    
    response.setContentType("YOUR CONTENT TYPE HERE");
    response.setHeader("Content-Disposition", "filename=\"THE FILE NAME\"");
    response.setContentLength(byteArray.length);
    OutputStream os = response.getOutputStream();
    
    try {
       os.write(byteArray , 0, byteArray.length);
    } catch (Exception excp) {
       //handle error
    } finally {
        os.close();
    }
    

    EDIT: I've noticed that you are first decoding your data from base64, the you should do the following:

    OutputStream os = response.getOutputStream();
    byte[] buffer = new byte[chunk];
    int bytesRead = -1;
    
    while ((bytesRead = base64InputStream.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
    }
    

    You do not need the intermediate ByteArrayOutputStream