Uploading a file in Jersey without using multipart

2019-09-20 07:02发布

问题:

I run a web service where I convert a file from one file format into another. The conversion logic is already functioning but now, I want to query this logic via Jersey. Whenever file upload via Jersey is addressed in tutorials / questions, people describe how to do this using multipart form data. I do however simply want to send and return a single file and skip the overhead of sending multiple parts. (The webservice is triggered by another machine which I control so there is no HTML form involved.)

My question is how would I achieve something like the following:

@POST
@Path("{sessionId"}
@Consumes("image/png")
@Produces("application/pdf")
public Response put(@PathParam("sessionId") String sessionId, 
                    @WhatToPutHere InputStream uploadedFileStream) {
  return BusinessLogic.convert(uploadedFile); // returns StreamingOutput - works!
}

How do I get hold of the uploadedFileStream (It should be some annotation, I guess which is of course not @WhatToPutHere). I figured out how to directly return a file via StreamingOutput.

Thanks for any help!

回答1:

You do not have to put anything in the second param of the function; just leave it un-annoted. The only thing you have to be carefull is to "name" the resource:

The resource should have an URI like: someSite/someRESTEndPoint/myResourceId so the function should be:

@POST
@Path("{myResourceId}")
@Consumes("image/png")
@Produces("application/pdf")
public Response put(@PathParam("myResourceId") String myResourceId, 
                                               InputStream uploadedFileStream) {
    return BusinessLogic.convert(uploadedFileStream); 
}

If you want to use some kind of SessionID, I'd prefer to use a Header Param... something like:

@POST
@Path("{myResourceId}")
@Consumes("image/png")
@Produces("application/pdf")
public Response put(@HeaderParam("sessionId") String sessionId,
                    @PathParam("myResourceId") String myResourceId, 
                                               InputStream uploadedFileStream) {
    return BusinessLogic.convert(uploadedFileStream); 
}