AndreaNobili
AndreaNobili

Reputation: 42957

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?

Upvotes: 6

Views: 21751

Answers (2)

user14972917
user14972917

Reputation:

With org.apache.commons.compress.utils.IOUtils you can just "copy" from one file or stream (e.g. your base64InputStream) to the output stream:

    response.setContentType([your file mime type]);
    IOUtils.copy(base64InputStream, response.getOutputStream());
    response.setStatus(HttpServletResponse.SC_OK);

You'll find that class here https://mvnrepository.com/artifact/org.apache.commons/commons-compress

A similar class (also named IOUtils) is also in Apache Commons IO (https://mvnrepository.com/artifact/commons-io/commons-io).

Upvotes: 0

Svetlin Zarev
Svetlin Zarev

Reputation: 15683

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

Upvotes: 18

Related Questions