Search in sources :

Example 21 with MultipartConfigElement

use of javax.servlet.MultipartConfigElement in project spring-framework by spring-projects.

the class RequestPartIntegrationTests method startServer.

@BeforeClass
public static void startServer() throws Exception {
    // Let server pick its own random, available port.
    server = new Server(0);
    ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");
    Class<?> config = CommonsMultipartResolverTestConfig.class;
    ServletHolder commonsResolverServlet = new ServletHolder(DispatcherServlet.class);
    commonsResolverServlet.setInitParameter("contextConfigLocation", config.getName());
    commonsResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    handler.addServlet(commonsResolverServlet, "/commons-resolver/*");
    config = StandardMultipartResolverTestConfig.class;
    ServletHolder standardResolverServlet = new ServletHolder(DispatcherServlet.class);
    standardResolverServlet.setInitParameter("contextConfigLocation", config.getName());
    standardResolverServlet.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
    standardResolverServlet.getRegistration().setMultipartConfig(new MultipartConfigElement(""));
    handler.addServlet(standardResolverServlet, "/standard-resolver/*");
    server.setHandler(handler);
    server.start();
    Connector[] connectors = server.getConnectors();
    NetworkConnector connector = (NetworkConnector) connectors[0];
    baseUrl = "http://localhost:" + connector.getLocalPort();
}
Also used : NetworkConnector(org.eclipse.jetty.server.NetworkConnector) Connector(org.eclipse.jetty.server.Connector) MultipartConfigElement(javax.servlet.MultipartConfigElement) Server(org.eclipse.jetty.server.Server) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) NetworkConnector(org.eclipse.jetty.server.NetworkConnector) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) AnnotationConfigWebApplicationContext(org.springframework.web.context.support.AnnotationConfigWebApplicationContext) BeforeClass(org.junit.BeforeClass)

Example 22 with MultipartConfigElement

use of javax.servlet.MultipartConfigElement in project undertow by undertow-io.

the class AddMultipartServetListener method contextInitialized.

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletRegistration.Dynamic reg = sce.getServletContext().addServlet("added", new MultiPartServlet());
    reg.addMapping("/added");
    reg.setMultipartConfig(new MultipartConfigElement(System.getProperty("java.io.tmpdir")));
}
Also used : ServletRegistration(javax.servlet.ServletRegistration) MultipartConfigElement(javax.servlet.MultipartConfigElement)

Example 23 with MultipartConfigElement

use of javax.servlet.MultipartConfigElement in project dropbox-sdk-java by dropbox.

the class DropboxBrowse method doUpload.

// -------------------------------------------------------------------------------------------
// POST /upload
// -------------------------------------------------------------------------------------------
public void doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/tmp");
    request.setAttribute("org.eclipse.multipartConfig", multipartConfigElement);
    if (!common.checkPost(request, response))
        return;
    User user = common.requireLoggedInUser(request, response);
    if (user == null)
        return;
    DbxClientV2 dbxClient = requireDbxClient(request, response, user);
    if (dbxClient == null)
        return;
    try {
        // Just call getParts() to trigger the too-large exception.
        request.getParts();
    } catch (IllegalStateException ex) {
        response.sendError(400, "Request too large");
        return;
    }
    String targetFolder = slurpUtf8Part(request, response, "targetFolder", 1024);
    if (targetFolder == null)
        return;
    Part filePart = request.getPart("file");
    if (filePart == null) {
        response.sendError(400, "Field \"file\" is missing.");
        return;
    }
    String fileName = filePart.getName();
    if (fileName == null) {
        response.sendError(400, "Field \"file\" has no name.");
        return;
    }
    // Upload file to Dropbox
    String fullTargetPath = targetFolder + "/" + fileName;
    FileMetadata metadata;
    try {
        metadata = dbxClient.files().upload(fullTargetPath).uploadAndFinish(filePart.getInputStream());
    } catch (DbxException ex) {
        common.handleDbxException(response, user, ex, "upload(" + jq(fullTargetPath) + ", ...)");
        return;
    } catch (IOException ex) {
        response.sendError(400, "Error getting file data from you.");
        return;
    }
    // Display uploaded file metadata.
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    out.println("<html>");
    out.println("<head><title>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</title></head>");
    out.println("<body>");
    out.println("<h2>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</h2>");
    out.println("<pre>");
    out.print(escapeHtml4(metadata.toStringMultiline()));
    out.println("</pre>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
}
Also used : DbxClientV2(com.dropbox.core.v2.DbxClientV2) MultipartConfigElement(javax.servlet.MultipartConfigElement) Part(javax.servlet.http.Part) FileMetadata(com.dropbox.core.v2.files.FileMetadata) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) DbxException(com.dropbox.core.DbxException) PrintWriter(java.io.PrintWriter)

Example 24 with MultipartConfigElement

use of javax.servlet.MultipartConfigElement 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.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;
            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 : ServletRequestContext(org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext) AsyncContext(javax.servlet.AsyncContext) Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) 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) ApplicationPart(org.apache.catalina.core.ApplicationPart) File(java.io.File) FileUploadException(org.apache.tomcat.util.http.fileupload.FileUploadException)

Example 25 with MultipartConfigElement

use of javax.servlet.MultipartConfigElement in project jetty.project by eclipse.

the class MultiPartInputStreamTest method testWhitespaceBodyWithCRLF.

@Test
public void testWhitespaceBodyWithCRLF() throws Exception {
    String whitespace = "              \n\n\n\r\n\r\n\r\n\r\n";
    MultipartConfigElement config = new MultipartConfigElement(_dirname, 1024, 3072, 50);
    MultiPartInputStreamParser mpis = new MultiPartInputStreamParser(new ByteArrayInputStream(whitespace.getBytes()), _contentType, config, _tmpDir);
    mpis.setDeleteOnExit(true);
    try {
        mpis.getParts();
        fail("Multipart missing body");
    } catch (IOException e) {
        assertTrue(e.getMessage().startsWith("Missing initial"));
    }
}
Also used : MultipartConfigElement(javax.servlet.MultipartConfigElement) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

MultipartConfigElement (javax.servlet.MultipartConfigElement)51 Test (org.junit.Test)35 ByteArrayInputStream (java.io.ByteArrayInputStream)30 Part (javax.servlet.http.Part)27 MultiPart (org.eclipse.jetty.util.MultiPartInputStreamParser.MultiPart)24 ByteArrayOutputStream (java.io.ByteArrayOutputStream)13 IOException (java.io.IOException)8 File (java.io.File)7 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)5 ServletException (javax.servlet.ServletException)4 ServletInputStream (javax.servlet.ServletInputStream)4 InputStream (java.io.InputStream)3 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Servlet (javax.servlet.Servlet)2 ServletRegistration (javax.servlet.ServletRegistration)2 MultipartConfig (javax.servlet.annotation.MultipartConfig)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 MultiPartInputStreamParser (org.eclipse.jetty.util.MultiPartInputStreamParser)2 DbxException (com.dropbox.core.DbxException)1