Geek
Geek

Reputation: 1405

Return a file in RestExpress response

I'm using RestExpress for creating my REST API. I have a situation in which i'm supposed to return a pdf file in the response so that end-user should be able to download it. I understand that this can be achieved via Servlets but the RestExpress has its own Response object, and it doesn't have response.getOutputStream() function supported. How do I achieve this functionality using RestExpress Response object?

Upvotes: 0

Views: 274

Answers (1)

Geek
Geek

Reputation: 1405

I was able to achieve this functionality using Unpooled Netty buffer. If you are using Netty 3.10 or older you may want to use ChannelBuffers instead of Pool class. In Netty 4.0/4.1 ChannelBuffers has been replaced by Unpooled.

Below is the sample code:

import io.netty.buffer.Unpooled;
import java.nio.file.Files;
import java.nio.file.Paths;

response.setContentType("application/pdf"); //Setting content type to be pdf
response.addHeader("Content-disposition", "attachment; filename=" + outputFileAddress);
LOG.info(outputFileAddress);       
java.nio.file.Path path = Paths.get(outputFileAddress);
byte[] data = Files.readAllBytes(path);
response.setBody(Unpooled.wrappedBuffer(data));
response.noSerialization(); // No serialization avoids getting the stream to Jackson
response.setResponseStatus(HttpResponseStatus.OK);

Upvotes: 1

Related Questions