How do I write a restful web service that accepts a binary file (pdf)

前端 未结 3 1619
后悔当初
后悔当初 2020-12-04 20:29

I\'m trying to write a restful web service in java that will take a few string params and a binary file (pdf) param.

I understand how to do the strings but I\'m get

3条回答
  •  难免孤独
    2020-12-04 20:49

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.TEXT_PLAIN)
    @Path("submit")
    public Response submit(@FormDataParam("clientID") String clientID,
                       @FormDataParam("html") String html,
                       @FormDataParam("pdf") InputStream pdfStream) {
    
        try {
            byte[] pdfByteArray = DocUtils.convertInputStreamToByteArrary(pdfStream);
        } catch (Exception ex) {
            return Response.status(600).entity(ex.getMessage()).build();
        }
    }
    
    
    ...
    
    public static byte[] convertInputStreamToByteArrary(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        final int BUF_SIZE = 1024;
        byte[] buffer = new byte[BUF_SIZE];
        int bytesRead = -1;
        while ((bytesRead = in.read(buffer)) > -1) {
            out.write(buffer, 0, bytesRead);
        }
        in.close();
        byte[] byteArray = out.toByteArray();
        return byteArray;
    }
    

提交回复
热议问题