I am building an application to download the PDF file from out back-end server. I have written following code:
On Backend Server, following is the method:
UPDATED:
The problem you are facing is because JS cannot handle binary data. Your best option is to base64 encode the file on your backend server and then base64 decode the file on your app before saving to a file. For Example:
Backend Server:
You will need an additional dependency in your project import org.apache.commons.codec.binary.Base64;
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/pdf")
public Response downloads() throws IOException {
File file = new File("myFile.pdf");
InputStream fileStream = new FileInputStream(file);
byte[] data = new byte[1024];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int read = 0;
while ((read = fileStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, read);
}
buffer.flush();
fileStream.close();
ResponseBuilder response = Response.ok(Base64.encodeBase64(buffer.toByteArray()));
response.header("Content-Disposition", "attachment; filename=myFile.pdf");
Response responseBuilder = response.build();
return responseBuilder;
}