Setting file size restrictions when uploading files with Jersey

后端 未结 5 1851
孤独总比滥情好
孤独总比滥情好 2021-01-04 08:42

I\'m currently implementing functionality for uploading files using jersey rest. I would like to set a maximum allowed file size which to me seems like a pretty common requi

5条回答
  •  日久生厌
    2021-01-04 09:18

    You can check the length, in bytes, of the request body and made available by the input stream with the following code:

    public Response uploadFile(@Context final HttpServletRequest request, @FormDataParam("uploadFile") InputStream uploadedInputStream,
          @FormDataParam("uploadFile") FormDataContentDisposition fileDetail, @FormDataParam("uploadFile") FormDataBodyPart body) {
    

    The key part being @Context final HttpServletRequest request. Then in the method body, you can get the length of the inputstream and react to it accordingly with:

    int contentLength = request.getContentLength();
    
    if (contentLength == -1 || contentLength > MAX_REQUEST_SIZE) {
      // deal with it
    }
    

提交回复
热议问题