Search in sources :

Example 1 with FileItem

use of org.apache.tomcat.util.http.fileupload.FileItem in project spring-framework by spring-projects.

the class FormHttpMessageConverterTests method writeMultipart.

@Test
public void writeMultipart() throws Exception {
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("name 1", "value 1");
    parts.add("name 2", "value 2+1");
    parts.add("name 2", "value 2+2");
    parts.add("name 3", null);
    Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
    parts.add("logo", logo);
    // SPR-12108
    Resource utf8 = new ClassPathResource("/org/springframework/http/converter/logo.jpg") {

        @Override
        public String getFilename() {
            return "Hall\u00F6le.jpg";
        }
    };
    parts.add("utf8", utf8);
    Source xml = new StreamSource(new StringReader("<root><child/></root>"));
    HttpHeaders entityHeaders = new HttpHeaders();
    entityHeaders.setContentType(TEXT_XML);
    HttpEntity<Source> entity = new HttpEntity<>(xml, entityHeaders);
    parts.add("xml", entity);
    Map<String, String> parameters = new LinkedHashMap<>(2);
    parameters.put("charset", StandardCharsets.UTF_8.name());
    parameters.put("foo", "bar");
    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    this.converter.write(parts, new MediaType("multipart", "form-data", parameters), outputMessage);
    final MediaType contentType = outputMessage.getHeaders().getContentType();
    // gh-21568, gh-25839
    assertThat(contentType.getParameters()).containsKeys("charset", "boundary", "foo");
    // see if Commons FileUpload can read what we wrote
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    FileUpload fileUpload = new FileUpload(fileItemFactory);
    RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
    List<FileItem> items = fileUpload.parseRequest(requestContext);
    assertThat(items.size()).isEqualTo(6);
    FileItem item = items.get(0);
    assertThat(item.isFormField()).isTrue();
    assertThat(item.getFieldName()).isEqualTo("name 1");
    assertThat(item.getString()).isEqualTo("value 1");
    item = items.get(1);
    assertThat(item.isFormField()).isTrue();
    assertThat(item.getFieldName()).isEqualTo("name 2");
    assertThat(item.getString()).isEqualTo("value 2+1");
    item = items.get(2);
    assertThat(item.isFormField()).isTrue();
    assertThat(item.getFieldName()).isEqualTo("name 2");
    assertThat(item.getString()).isEqualTo("value 2+2");
    item = items.get(3);
    assertThat(item.isFormField()).isFalse();
    assertThat(item.getFieldName()).isEqualTo("logo");
    assertThat(item.getName()).isEqualTo("logo.jpg");
    assertThat(item.getContentType()).isEqualTo("image/jpeg");
    assertThat(item.getSize()).isEqualTo(logo.getFile().length());
    item = items.get(4);
    assertThat(item.isFormField()).isFalse();
    assertThat(item.getFieldName()).isEqualTo("utf8");
    assertThat(item.getName()).isEqualTo("Hall\u00F6le.jpg");
    assertThat(item.getContentType()).isEqualTo("image/jpeg");
    assertThat(item.getSize()).isEqualTo(logo.getFile().length());
    item = items.get(5);
    assertThat(item.getFieldName()).isEqualTo("xml");
    assertThat(item.getContentType()).isEqualTo("text/xml");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) StreamSource(javax.xml.transform.stream.StreamSource) MockHttpOutputMessage(org.springframework.http.MockHttpOutputMessage) ClassPathResource(org.springframework.core.io.ClassPathResource) Resource(org.springframework.core.io.Resource) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) ClassPathResource(org.springframework.core.io.ClassPathResource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) FileItemFactory(org.apache.tomcat.util.http.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) LinkedHashMap(java.util.LinkedHashMap) FileItem(org.apache.tomcat.util.http.fileupload.FileItem) StringReader(java.io.StringReader) MediaType(org.springframework.http.MediaType) RequestContext(org.apache.tomcat.util.http.fileupload.RequestContext) FileUpload(org.apache.tomcat.util.http.fileupload.FileUpload) Test(org.junit.jupiter.api.Test)

Example 2 with FileItem

use of org.apache.tomcat.util.http.fileupload.FileItem in project tomcat70 by apache.

the class Request method parseParts.

private void parseParts() {
    // Return immediately if the parts have already been parsed
    if (parts != null || partsParseException != null) {
        return;
    }
    MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
    if (mce == null) {
        if (getContext().getAllowCasualMultipartParsing()) {
            mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize());
        } else {
            parts = Collections.emptyList();
            return;
        }
    }
    Parameters parameters = coyoteRequest.getParameters();
    parameters.setLimit(getConnector().getMaxParameterCount());
    boolean success = false;
    try {
        File location;
        String locationStr = mce.getLocation();
        if (locationStr == null || locationStr.length() == 0) {
            location = ((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR));
        } else {
            // If relative, it is relative to TEMPDIR
            location = new File(locationStr);
            if (!location.isAbsolute()) {
                location = new File((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR), locationStr).getAbsoluteFile();
            }
        }
        if (!location.isDirectory()) {
            parameters.setParseFailedReason(FailReason.MULTIPART_CONFIG_INVALID);
            partsParseException = new IOException(sm.getString("coyoteRequest.uploadLocationInvalid", location));
            return;
        }
        // Create a new file upload handler
        DiskFileItemFactory factory = new DiskFileItemFactory();
        try {
            factory.setRepository(location.getCanonicalFile());
        } catch (IOException ioe) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = ioe;
            return;
        }
        factory.setSizeThreshold(mce.getFileSizeThreshold());
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        upload.setFileSizeMax(mce.getMaxFileSize());
        upload.setSizeMax(mce.getMaxRequestSize());
        parts = new ArrayList<Part>();
        try {
            List<FileItem> items = upload.parseRequest(new ServletRequestContext(this));
            int maxPostSize = getConnector().getMaxPostSize();
            int postSize = 0;
            String enc = getCharacterEncoding();
            Charset charset = null;
            if (enc != null) {
                try {
                    charset = B2CConverter.getCharset(enc);
                } catch (UnsupportedEncodingException e) {
                // Ignore
                }
            }
            for (FileItem item : items) {
                ApplicationPart part = new ApplicationPart(item, location);
                parts.add(part);
                if (part.getSubmittedFileName() == null) {
                    String name = part.getName();
                    String value = null;
                    try {
                        String encoding = parameters.getEncoding();
                        if (encoding == null) {
                            if (enc == null) {
                                encoding = Parameters.DEFAULT_ENCODING;
                            } else {
                                encoding = enc;
                            }
                        }
                        value = part.getString(encoding);
                    } catch (UnsupportedEncodingException uee) {
                        try {
                            value = part.getString(Parameters.DEFAULT_ENCODING);
                        } catch (UnsupportedEncodingException e) {
                        // Should not be possible
                        }
                    }
                    if (maxPostSize >= 0) {
                        // accurate but close enough.
                        if (charset == null) {
                            // Name length
                            postSize += name.getBytes().length;
                        } else {
                            postSize += name.getBytes(charset).length;
                        }
                        if (value != null) {
                            // Equals sign
                            postSize++;
                            // Value length
                            postSize += part.getSize();
                        }
                        // Value separator
                        postSize++;
                        if (postSize > maxPostSize) {
                            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                            throw new IllegalStateException(sm.getString("coyoteRequest.maxPostSizeExceeded"));
                        }
                    }
                    parameters.addParameter(name, value);
                }
            }
            success = true;
        } catch (InvalidContentTypeException e) {
            parameters.setParseFailedReason(FailReason.INVALID_CONTENT_TYPE);
            partsParseException = new ServletException(e);
        } catch (FileUploadBase.SizeException e) {
            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
            checkSwallowInput();
            partsParseException = new IllegalStateException(e);
        } catch (FileUploadException e) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = new IOException(e);
        } catch (IllegalStateException e) {
            // addParameters() will set parseFailedReason
            checkSwallowInput();
            partsParseException = e;
        }
    } finally {
        if (partsParseException != null || !success) {
            parameters.setParseFailedReason(FailReason.UNKNOWN);
        }
    }
}
Also used : Parameters(org.apache.tomcat.util.http.Parameters) InvalidContentTypeException(org.apache.tomcat.util.http.fileupload.FileUploadBase.InvalidContentTypeException) ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) FileItem(org.apache.tomcat.util.http.fileupload.FileItem) MultipartConfigElement(javax.servlet.MultipartConfigElement) ServletFileUpload(org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload) FileUploadBase(org.apache.tomcat.util.http.fileupload.FileUploadBase) Part(javax.servlet.http.Part) ApplicationPart(org.apache.catalina.core.ApplicationPart) ApplicationPart(org.apache.catalina.core.ApplicationPart) File(java.io.File) FileUploadException(org.apache.tomcat.util.http.fileupload.FileUploadException)

Example 3 with FileItem

use of org.apache.tomcat.util.http.fileupload.FileItem in project spring-framework by spring-projects.

the class FormHttpMessageConverterTests method writeMultipartOrder.

// SPR-13309
@Test
public void writeMultipartOrder() throws Exception {
    MyBean myBean = new MyBean();
    myBean.setString("foo");
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    parts.add("part1", myBean);
    HttpHeaders entityHeaders = new HttpHeaders();
    entityHeaders.setContentType(TEXT_XML);
    HttpEntity<MyBean> entity = new HttpEntity<>(myBean, entityHeaders);
    parts.add("part2", entity);
    MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
    this.converter.setMultipartCharset(StandardCharsets.UTF_8);
    this.converter.write(parts, new MediaType("multipart", "form-data", StandardCharsets.UTF_8), outputMessage);
    final MediaType contentType = outputMessage.getHeaders().getContentType();
    assertThat(contentType.getParameter("boundary")).as("No boundary found").isNotNull();
    // see if Commons FileUpload can read what we wrote
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    FileUpload fileUpload = new FileUpload(fileItemFactory);
    RequestContext requestContext = new MockHttpOutputMessageRequestContext(outputMessage);
    List<FileItem> items = fileUpload.parseRequest(requestContext);
    assertThat(items.size()).isEqualTo(2);
    FileItem item = items.get(0);
    assertThat(item.isFormField()).isTrue();
    assertThat(item.getFieldName()).isEqualTo("part1");
    assertThat(item.getString()).isEqualTo("{\"string\":\"foo\"}");
    item = items.get(1);
    assertThat(item.isFormField()).isTrue();
    assertThat(item.getFieldName()).isEqualTo("part2");
    // With developer builds we get: <MyBean><string>foo</string></MyBean>
    // But on CI server we get: <MyBean xmlns=""><string>foo</string></MyBean>
    // So... we make a compromise:
    assertThat(item.getString()).startsWith("<MyBean").endsWith("><string>foo</string></MyBean>");
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) MockHttpOutputMessage(org.springframework.http.MockHttpOutputMessage) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.tomcat.util.http.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.tomcat.util.http.fileupload.FileItem) MediaType(org.springframework.http.MediaType) RequestContext(org.apache.tomcat.util.http.fileupload.RequestContext) FileUpload(org.apache.tomcat.util.http.fileupload.FileUpload) Test(org.junit.jupiter.api.Test)

Example 4 with FileItem

use of org.apache.tomcat.util.http.fileupload.FileItem in project tomcat by apache.

the class FileItemIteratorImpl method getFileItems.

@Override
public List<FileItem> getFileItems() throws FileUploadException, IOException {
    final List<FileItem> items = new ArrayList<>();
    while (hasNext()) {
        final FileItemStream fis = next();
        final FileItem fi = fileUploadBase.getFileItemFactory().createItem(fis.getFieldName(), fis.getContentType(), fis.isFormField(), fis.getName());
        items.add(fi);
    }
    return items;
}
Also used : FileItem(org.apache.tomcat.util.http.fileupload.FileItem) FileItemStream(org.apache.tomcat.util.http.fileupload.FileItemStream) ArrayList(java.util.ArrayList)

Example 5 with FileItem

use of org.apache.tomcat.util.http.fileupload.FileItem in project tomcat by apache.

the class Request method parseParts.

private void parseParts(boolean explicit) {
    // Return immediately if the parts have already been parsed
    if (parts != null || partsParseException != null) {
        return;
    }
    Context context = getContext();
    MultipartConfigElement mce = getWrapper().getMultipartConfigElement();
    if (mce == null) {
        if (context.getAllowCasualMultipartParsing()) {
            mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize());
        } else {
            if (explicit) {
                partsParseException = new IllegalStateException(sm.getString("coyoteRequest.noMultipartConfig"));
                return;
            } else {
                parts = Collections.emptyList();
                return;
            }
        }
    }
    Parameters parameters = coyoteRequest.getParameters();
    parameters.setLimit(getConnector().getMaxParameterCount());
    boolean success = false;
    try {
        File location;
        String locationStr = mce.getLocation();
        if (locationStr == null || locationStr.length() == 0) {
            location = ((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR));
        } else {
            // If relative, it is relative to TEMPDIR
            location = new File(locationStr);
            if (!location.isAbsolute()) {
                location = new File((File) context.getServletContext().getAttribute(ServletContext.TEMPDIR), locationStr).getAbsoluteFile();
            }
        }
        if (!location.exists() && context.getCreateUploadTargets()) {
            log.warn(sm.getString("coyoteRequest.uploadCreate", location.getAbsolutePath(), getMappingData().wrapper.getName()));
            if (!location.mkdirs()) {
                log.warn(sm.getString("coyoteRequest.uploadCreateFail", location.getAbsolutePath()));
            }
        }
        if (!location.isDirectory()) {
            parameters.setParseFailedReason(FailReason.MULTIPART_CONFIG_INVALID);
            partsParseException = new IOException(sm.getString("coyoteRequest.uploadLocationInvalid", location));
            return;
        }
        // Create a new file upload handler
        DiskFileItemFactory factory = new DiskFileItemFactory();
        try {
            factory.setRepository(location.getCanonicalFile());
        } catch (IOException ioe) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = ioe;
            return;
        }
        factory.setSizeThreshold(mce.getFileSizeThreshold());
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(factory);
        upload.setFileSizeMax(mce.getMaxFileSize());
        upload.setSizeMax(mce.getMaxRequestSize());
        parts = new ArrayList<>();
        try {
            List<FileItem> items = upload.parseRequest(new ServletRequestContext(this));
            int maxPostSize = getConnector().getMaxPostSize();
            int postSize = 0;
            Charset charset = getCharset();
            for (FileItem item : items) {
                ApplicationPart part = new ApplicationPart(item, location);
                parts.add(part);
                if (part.getSubmittedFileName() == null) {
                    String name = part.getName();
                    if (maxPostSize >= 0) {
                        // Have to calculate equivalent size. Not completely
                        // accurate but close enough.
                        postSize += name.getBytes(charset).length;
                        // Equals sign
                        postSize++;
                        // Value length
                        postSize += part.getSize();
                        // Value separator
                        postSize++;
                        if (postSize > maxPostSize) {
                            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
                            throw new IllegalStateException(sm.getString("coyoteRequest.maxPostSizeExceeded"));
                        }
                    }
                    String value = null;
                    try {
                        value = part.getString(charset.name());
                    } catch (UnsupportedEncodingException uee) {
                    // Not possible
                    }
                    parameters.addParameter(name, value);
                }
            }
            success = true;
        } catch (InvalidContentTypeException e) {
            parameters.setParseFailedReason(FailReason.INVALID_CONTENT_TYPE);
            partsParseException = new ServletException(e);
        } catch (SizeException e) {
            parameters.setParseFailedReason(FailReason.POST_TOO_LARGE);
            checkSwallowInput();
            partsParseException = new IllegalStateException(e);
        } catch (IOException e) {
            parameters.setParseFailedReason(FailReason.IO_ERROR);
            partsParseException = new IOException(e);
        } catch (IllegalStateException e) {
            // addParameters() will set parseFailedReason
            checkSwallowInput();
            partsParseException = e;
        }
    } finally {
        // respect to changes in the remainder of the method.
        if (partsParseException != null || !success) {
            parameters.setParseFailedReason(FailReason.UNKNOWN);
        }
    }
}
Also used : ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) ServletContext(jakarta.servlet.ServletContext) AsyncContext(jakarta.servlet.AsyncContext) Context(org.apache.catalina.Context) Parameters(org.apache.tomcat.util.http.Parameters) InvalidContentTypeException(org.apache.tomcat.util.http.fileupload.impl.InvalidContentTypeException) ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) Charset(java.nio.charset.Charset) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) DiskFileItemFactory(org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory) ServletException(jakarta.servlet.ServletException) FileItem(org.apache.tomcat.util.http.fileupload.FileItem) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) ServletFileUpload(org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload) ApplicationPart(org.apache.catalina.core.ApplicationPart) File(java.io.File) SizeException(org.apache.tomcat.util.http.fileupload.impl.SizeException)

Aggregations

FileItem (org.apache.tomcat.util.http.fileupload.FileItem)5 DiskFileItemFactory (org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory)4 File (java.io.File)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Charset (java.nio.charset.Charset)2 ApplicationPart (org.apache.catalina.core.ApplicationPart)2 Parameters (org.apache.tomcat.util.http.Parameters)2 FileItemFactory (org.apache.tomcat.util.http.fileupload.FileItemFactory)2 FileUpload (org.apache.tomcat.util.http.fileupload.FileUpload)2 RequestContext (org.apache.tomcat.util.http.fileupload.RequestContext)2 ServletFileUpload (org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload)2 ServletRequestContext (org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext)2 Test (org.junit.jupiter.api.Test)2 HttpEntity (org.springframework.http.HttpEntity)2 HttpHeaders (org.springframework.http.HttpHeaders)2 MediaType (org.springframework.http.MediaType)2 MockHttpOutputMessage (org.springframework.http.MockHttpOutputMessage)2 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)2 AsyncContext (jakarta.servlet.AsyncContext)1