Download PDF file from through MobileFirst Adapter

后端 未结 1 1786
醉梦人生
醉梦人生 2020-12-22 12:14

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:

         


        
相关标签:
1条回答
  • 2020-12-22 13:10

    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;
    }
    
    0 讨论(0)
提交回复
热议问题