File upload endpoint need to close InputStream?

懵懂的女人 提交于 2021-02-18 18:20:07

问题


@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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!