Search in sources :

Example 1 with FileSizeLimitExceededException

use of com.helger.web.fileupload.exception.FileSizeLimitExceededException in project ph-web by phax.

the class SizesFuncTest method testFileSizeLimit.

/**
 * Checks, whether limiting the file size works.
 *
 * @throws FileUploadException
 *         In case of error
 */
@Test
public void testFileSizeLimit() throws FileUploadException {
    final String request = "-----1234\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"foo.tab\"\r\n" + "Content-Type: text/whatever\r\n" + "\r\n" + "This is the content of the file\n" + "\r\n" + "-----1234--\r\n";
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory(10240));
    upload.setFileSizeMax(-1);
    HttpServletRequest req = new MockHttpServletRequest().setContent(request.getBytes(StandardCharsets.US_ASCII)).setContentType(CONTENT_TYPE);
    List<IFileItem> fileItems = upload.parseRequest(req);
    assertEquals(1, fileItems.size());
    IFileItem item = fileItems.get(0);
    assertEquals("This is the content of the file\n", new String(item.directGet(), StandardCharsets.US_ASCII));
    upload = new ServletFileUpload(new DiskFileItemFactory(10240));
    upload.setFileSizeMax(40);
    req = new MockHttpServletRequest().setContent(request.getBytes(StandardCharsets.US_ASCII)).setContentType(CONTENT_TYPE);
    fileItems = upload.parseRequest(req);
    assertEquals(1, fileItems.size());
    item = fileItems.get(0);
    assertEquals("This is the content of the file\n", new String(item.directGet(), StandardCharsets.US_ASCII));
    upload = new ServletFileUpload(new DiskFileItemFactory(10240));
    upload.setFileSizeMax(30);
    req = new MockHttpServletRequest().setContent(request.getBytes(StandardCharsets.US_ASCII)).setContentType(CONTENT_TYPE);
    try {
        upload.parseRequest(req);
        fail("Expected exception.");
    } catch (final FileSizeLimitExceededException e) {
        assertEquals(30, e.getPermittedSize());
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) MockHttpServletRequest(com.helger.servlet.mock.MockHttpServletRequest) FileSizeLimitExceededException(com.helger.web.fileupload.exception.FileSizeLimitExceededException) IFileItem(com.helger.web.fileupload.IFileItem) DiskFileItemFactory(com.helger.web.fileupload.parse.DiskFileItemFactory) Test(org.junit.Test)

Aggregations

MockHttpServletRequest (com.helger.servlet.mock.MockHttpServletRequest)1 IFileItem (com.helger.web.fileupload.IFileItem)1 FileSizeLimitExceededException (com.helger.web.fileupload.exception.FileSizeLimitExceededException)1 DiskFileItemFactory (com.helger.web.fileupload.parse.DiskFileItemFactory)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 Test (org.junit.Test)1