问题
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload")
public String upload(@FormDataParam("file") InputStream inputStream) {
...
inputStream.close(); // necessary?
}
For an API endpoint that accepts a file input, do we need to manually close the InputStream
or does the framework do it for us?
I have checked the Jersey docs but could not find any information about it.
Looking for credible source or some way to validate it.
回答1:
It is your responsibility to close InputStream.
Jersey intrinsically cannot know when to close your stream.
回答2:
1) after you consumed the InputStream you can assume that it's safe to close it.
2) You can also register the InputStream with the Jersey ClosableService, according to its documentation it will close the InputStream for you. ClosableService
I hope that helps.
回答3:
I just wondered the same thing and tried it out in the debugger. Jersey does not close the stream for you.
I think the most elegant way is to use try-with-resources, which can take arbitrary expressions since Java 9 and calls close()
for you.
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/upload")
public String upload(@FormDataParam("file") InputStream inputStream) {
...
try (inputStream) {
//...
} catch (IOException e) {
//...
}
来源:https://stackoverflow.com/questions/50672835/file-upload-endpoint-need-to-close-inputstream