下面列出了怎么用javax.servlet.MultipartConfigElement的API类实例代码及写法,或者点击链接到github查看源代码。
private synchronized void init() throws Exception {
if (init) return;
Tomcat tomcat = getTomcatInstance();
context = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(context, "regular", new Bug49711Servlet());
Wrapper w = Tomcat.addServlet(context, "multipart", new Bug49711Servlet_multipart());
// Tomcat.addServlet does not respect annotations, so we have
// to set our own MultipartConfigElement.
w.setMultipartConfigElement(new MultipartConfigElement(""));
context.addServletMappingDecoded("/regular", "regular");
context.addServletMappingDecoded("/multipart", "multipart");
tomcat.start();
setPort(tomcat.getConnector().getLocalPort());
init = true;
}
protected ServletContextHandler createPippoHandler() {
MultipartConfigElement multipartConfig = createMultipartConfigElement();
ServletContextHandler handler = new PippoHandler(ServletContextHandler.SESSIONS, multipartConfig);
handler.setContextPath(getSettings().getContextPath());
// inject application as context attribute
handler.setAttribute(PIPPO_APPLICATION, getApplication());
// add pippo filter
addPippoFilter(handler);
// add initializers
handler.addEventListener(new PippoServletContextListener());
// all listeners
listeners.forEach(listener -> {
try {
handler.addEventListener(listener.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
throw new PippoRuntimeException(e);
}
});
return handler;
}
/**
* Initializes Spring and Spring MVC.
*/
private ServletRegistration.Dynamic initSpring(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext) {
LOGGER.debug("Configuring Spring Web application context");
AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
dispatcherServletConfiguration.setParent(rootContext);
dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);
LOGGER.debug("Registering Spring MVC Servlet");
ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
dispatcherServlet.addMapping("/service/*");
dispatcherServlet.setMultipartConfig(new MultipartConfigElement((String) null));
dispatcherServlet.setLoadOnStartup(1);
dispatcherServlet.setAsyncSupported(true);
return dispatcherServlet;
}
@Override
public void accept(final Context context) {
final Configuration config = instance.getConfiguration().getExtension(Configuration.class);
if (config.skip) {
return;
}
context.addServletContainerInitializer((c, ctx) -> {
final ServletRegistration.Dynamic servlet = ctx.addServlet("meecrowave-proxy-servlet", CDIProxyServlet.class);
servlet.setLoadOnStartup(1);
servlet.setAsyncSupported(true);
servlet.addMapping(config.mapping);
if (config.multipart) {
servlet.setMultipartConfig(new MultipartConfigElement(
config.multipartLocation,
config.multipartMaxFileSize,
config.multipartMaxRequestSize,
config.multipartFileSizeThreshold));
}
servlet.setInitParameter("mapping", config.mapping);
servlet.setInitParameter("configuration", config.configuration);
}, null);
}
public void start () throws ServletException, NamespaceException
{
final BundleContext bundleContext = FrameworkUtil.getBundle ( DispatcherServletInitializer.class ).getBundleContext ();
this.context = Dispatcher.createContext ( bundleContext );
this.errorHandler = new ErrorHandlerTracker ();
Dictionary<String, String> initparams = new Hashtable<> ();
final MultipartConfigElement multipart = Servlets.createMultiPartConfiguration ( PROP_PREFIX_MP );
final DispatcherServlet servlet = new DispatcherServlet ();
servlet.setErrorHandler ( this.errorHandler );
this.webContainer.registerServlet ( servlet, "dispatcher", new String[] { "/" }, initparams, 1, false, multipart, this.context );
this.proxyFilter = new FilterTracker ( bundleContext );
this.webContainer.registerFilter ( this.proxyFilter, new String[] { "/*" }, null, null, this.context );
initparams = new Hashtable<> ();
initparams.put ( "filter-mapping-dispatcher", "request" );
this.webContainer.registerFilter ( new BundleFilter (), new String[] { "/bundle/*" }, null, initparams, this.context );
this.jspTracker = new BundleTracker<> ( bundleContext, Bundle.INSTALLED | Bundle.ACTIVE, new JspBundleCustomizer ( this.webContainer, this.context ) );
this.jspTracker.open ();
}
protected void createSpringServlet(ServletContext servletContext) {
log.info("Creating Spring Servlet started....");
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(
WebMvcConfig.class
);
DispatcherServlet sc = new DispatcherServlet(appContext);
ServletRegistration.Dynamic appServlet = servletContext.addServlet("DispatcherServlet", sc);
appServlet.setLoadOnStartup(1);
appServlet.addMapping("/");
// for serving up asynchronous events in tomcat
appServlet.setInitParameter("dispatchOptionsRequest", "true");
appServlet.setAsyncSupported(true);
// enable multipart file upload support
// file size limit is 10Mb
// max file request size = 20Mb
appServlet.setMultipartConfig(new MultipartConfigElement("/tmp", 10000000l, 20000000l, 0));
// log.info("Creating Spring Servlet completed");
}
@Override
public void handle(String url, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
Map<String, TestServerResponse> responses = findResponses(request);
MultipartConfigElement multipartConfigElement = new MultipartConfigElement((String) null);
request.setAttribute(Request.MULTIPART_CONFIG_ELEMENT, multipartConfigElement);
TestServerResponse testServerResponse = responses.get(baseRequest.getOriginalURI());
if (testServerResponse == null) {
response.setStatus(404);
} else {
testServerResponse.responseHeader(request).forEach(response::addHeader);
byte[] responseBody = testServerResponse.responseBody(request);
response.setStatus(testServerResponse.responseStatusCode());
response.setContentType(testServerResponse.responseType(request));
if (responseBody != null) {
response.getOutputStream().write(responseBody);
}
}
baseRequest.setHandled(true);
}
/**
* Initializes Spring and Spring MVC.
*/
private ServletRegistration.Dynamic initSpring(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext) {
LOGGER.debug("Configuring Spring Web application context");
AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
dispatcherServletConfiguration.setParent(rootContext);
dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);
LOGGER.debug("Registering Spring MVC Servlet");
ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
dispatcherServlet.addMapping("/service/*");
dispatcherServlet.setMultipartConfig(new MultipartConfigElement((String) null));
dispatcherServlet.setLoadOnStartup(1);
dispatcherServlet.setAsyncSupported(true);
return dispatcherServlet;
}
/**
* Initializes Spring and Spring MVC.
*/
private ServletRegistration.Dynamic initSpring(ServletContext servletContext, AnnotationConfigWebApplicationContext rootContext) {
LOGGER.debug("Configuring Spring Web application context");
AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
dispatcherServletConfiguration.setParent(rootContext);
dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);
LOGGER.debug("Registering Spring MVC Servlet");
ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherServletConfiguration));
dispatcherServlet.addMapping("/service/*");
dispatcherServlet.setMultipartConfig(new MultipartConfigElement((String) null));
dispatcherServlet.setLoadOnStartup(1);
dispatcherServlet.setAsyncSupported(true);
return dispatcherServlet;
}
static void setServletParameters(ServletContext servletContext) {
UploadConfig uploadConfig = new UploadConfig();
MultipartConfigElement multipartConfig = uploadConfig.toMultipartConfigElement();
if (multipartConfig == null) {
return;
}
File dir = createUploadDir(servletContext, multipartConfig.getLocation());
LOGGER.info("set uploads directory to \"{}\".", dir.getAbsolutePath());
List<ServletRegistration> servlets = findServletRegistrations(servletContext, RestServlet.class);
for (ServletRegistration servletRegistration : servlets) {
if (!Dynamic.class.isInstance(servletRegistration)) {
continue;
}
Dynamic dynamic = (Dynamic) servletRegistration;
dynamic.setMultipartConfig(multipartConfig);
}
}
@Test
public void getMultipartConfig_default() {
ArchaiusUtils.setProperty(RestConst.UPLOAD_DIR, "upload");
UploadConfig uploadConfig = new UploadConfig();
MultipartConfigElement multipartConfigElement = uploadConfig.toMultipartConfigElement();
Assert.assertEquals("upload", uploadConfig.getLocation());
Assert.assertEquals(-1L, uploadConfig.getMaxFileSize());
Assert.assertEquals(-1L, uploadConfig.getMaxSize());
Assert.assertEquals(0, uploadConfig.getFileSizeThreshold());
Assert.assertEquals("upload", multipartConfigElement.getLocation());
Assert.assertEquals(-1L, multipartConfigElement.getMaxFileSize());
Assert.assertEquals(-1L, multipartConfigElement.getMaxRequestSize());
Assert.assertEquals(0, multipartConfigElement.getFileSizeThreshold());
}
@Test
public void getMultipartConfig_config() {
ArchaiusUtils.setProperty(RestConst.UPLOAD_DIR, "upload");
ArchaiusUtils.setProperty(RestConst.UPLOAD_MAX_FILE_SIZE, 1);
ArchaiusUtils.setProperty(RestConst.UPLOAD_MAX_SIZE, 2);
ArchaiusUtils.setProperty(RestConst.UPLOAD_FILE_SIZE_THRESHOLD, 3);
UploadConfig uploadConfig = new UploadConfig();
MultipartConfigElement multipartConfigElement = uploadConfig.toMultipartConfigElement();
Assert.assertEquals("upload", uploadConfig.getLocation());
Assert.assertEquals(1, uploadConfig.getMaxFileSize());
Assert.assertEquals(2, uploadConfig.getMaxSize());
Assert.assertEquals(3, uploadConfig.getFileSizeThreshold());
Assert.assertEquals("upload", multipartConfigElement.getLocation());
Assert.assertEquals(1, multipartConfigElement.getMaxFileSize());
Assert.assertEquals(2, multipartConfigElement.getMaxRequestSize());
Assert.assertEquals(3, multipartConfigElement.getFileSizeThreshold());
}
private synchronized void init() throws Exception {
if (init) return;
Tomcat tomcat = getTomcatInstance();
context = tomcat.addContext("", TEMP_DIR);
Tomcat.addServlet(context, "regular", new Bug49711Servlet());
Wrapper w = Tomcat.addServlet(context, "multipart", new Bug49711Servlet_multipart());
// Tomcat.addServlet does not respect annotations, so we have
// to set our own MultipartConfigElement.
w.setMultipartConfigElement(new MultipartConfigElement(""));
context.addServletMapping("/regular", "regular");
context.addServletMapping("/multipart", "multipart");
tomcat.start();
setPort(tomcat.getConnector().getLocalPort());
init = true;
}
@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();
}
private void registerServlet( final Servlet servlet )
{
final ServletHolder holder = new ServletHolder( servlet );
this.handler.addServlet( holder, "/*" );
final String location = Files.createTempDir().getAbsolutePath();
final MultipartConfigElement multipartConfig = new MultipartConfigElement( location );
holder.getRegistration().setMultipartConfig( multipartConfig );
}
private synchronized void init(boolean limited, boolean swallow)
throws Exception {
Tomcat tomcat = getTomcatInstance();
context = tomcat.addContext("", TEMP_DIR);
Wrapper w;
w = Tomcat.addServlet(context, servletName,
new AbortedUploadServlet());
// Tomcat.addServlet does not respect annotations, so we have
// to set our own MultipartConfigElement.
// Choose upload file size limit.
if (limited) {
w.setMultipartConfigElement(new MultipartConfigElement("",
limitSize, -1, -1));
} else {
w.setMultipartConfigElement(new MultipartConfigElement(""));
}
context.addServletMappingDecoded(URI, servletName);
context.setSwallowAbortedUploads(swallow);
Connector c = tomcat.getConnector();
c.setMaxPostSize(2 * hugeSize);
c.setProperty("maxSwallowSize", Integer.toString(hugeSize));
tomcat.start();
setPort(c.getLocalPort());
}
/**
* 这个bean是为了自定义上传路径
* @return
*/
@Bean
MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setLocation(PathsUtils.getAbsolutePath(""));
return factory.createMultipartConfig();
}
@Bean
public ServletRegistrationBean<DispatcherServlet> actionEngineTestDispatcherServlet(ApplicationContext applicationContext) {
AnnotationConfigWebApplicationContext dispatcherServletConfiguration = new AnnotationConfigWebApplicationContext();
dispatcherServletConfiguration.setParent(applicationContext);
dispatcherServletConfiguration.register(DispatcherServletConfiguration.class);
DispatcherServlet servlet = new DispatcherServlet(dispatcherServletConfiguration);
ServletRegistrationBean<DispatcherServlet> registrationBean = new ServletRegistrationBean<>(servlet, "/service/*");
registrationBean.setName("External Job Test Servlet");
registrationBean.setMultipartConfig(new MultipartConfigElement((String) null));
registrationBean.setLoadOnStartup(1);
registrationBean.setAsyncSupported(true);
return registrationBean;
}
@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();
}
public MultipartRequestParser(int uploadLimitKB) {
multipartConfigElement = new MultipartConfigElement(
null, // temp dir (null=default)
-1, // maxFileSize (-1=none)
uploadLimitKB * 1024, // maxRequestSize
100 * 1024 ); // fileSizeThreshold after which will go to disk
}
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
long maxFileSize=524288000; //500MB
long maxRequestSize=524288000; //500MB
factory.setMaxFileSize(maxFileSize);
factory.setMaxRequestSize(maxRequestSize);
return factory.createMultipartConfig();
}
private void verifyMultipartServlet() {
ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
MultipartConfigElement multipart = src.getServletPathMatch().getServletChain().getManagedServlet().getMultipartConfig();
if (multipart == null) {
throw UndertowServletMessages.MESSAGES.multipartConfigNotPresent();
}
}
@Bean
@ConditionalOnMissingBean
public MultipartConfigElement multipartConfigElement() {
String location = multipartProperties.getLocation();
if(StringUtils.isBlank(location)){
location = LangUtils.isWindowsOS()?FileUtils.getJavaIoTmpdir():DEFAULT_TMP_DIR;
location = location + "/sb.tomcat."+serverProperties.getPort();
String pid = getPid();
if(StringUtils.isNotBlank(pid)){
location = location + ".pid" + pid;
}
try {
File dir = new File(FileUtils.convertDir(location));
if(!dir.exists()){
if(dir.mkdirs()){
dir.deleteOnExit();
this.multipartProperties.setLocation(dir.getPath());
}
}else{
this.multipartProperties.setLocation(dir.getPath());
}
} catch (Exception e) {
logger.error("create multipart temp location error: " + e.getMessage());
}
}
if(logger.isInfoEnabled()){
logger.info("multipart temp location: {}", this.multipartProperties.getLocation());
}
return this.multipartProperties.createMultipartConfig();
}
public PartImpl(final String name, final FormData.FormValue formValue, MultipartConfigElement config,
ServletContextImpl servletContext, HttpServletRequestImpl servletRequest) {
this.name = name;
this.formValue = formValue;
this.config = config;
this.servletContext = servletContext;
this.servletRequest = servletRequest;
}
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize("50MB"); //KB,MB
factory.setMaxRequestSize("100MB");
return factory.createMultipartConfig();
}
public void start () throws ServletException
{
this.uploadV2 = new UploadServletV2 ();
this.uploadV3 = new UploadServletV3 ();
final MultipartConfigElement mp = Servlets.createMultiPartConfiguration ( "drone.upload.servlet" );
this.webContainer.registerServlet ( this.uploadV2, "uploadV2", new String[] { "/api/v2/upload/*" }, null, 1, false, mp, null );
this.webContainer.registerServlet ( this.uploadV3, "uploadV3", new String[] { UploadServletV3.BASE_PATH + "/*" }, null, 1, false, mp, null );
}
/**
* 文件上传配置
*
* @return
*/
@Bean
public MultipartConfigElement multipartConfigElement()
{
MultipartConfigFactory factory = new MultipartConfigFactory();
//文件最大
factory.setMaxFileSize("10240KB"); //KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize("102400KB");
return factory.createMultipartConfig();
}
protected DeploymentManager createPippoDeploymentManager() {
DeploymentInfo info = Servlets.deployment();
info.setDeploymentName("Pippo");
info.setClassLoader(this.getClass().getClassLoader());
info.setContextPath(getSettings().getContextPath());
info.setIgnoreFlush(true);
// inject application as context attribute
info.addServletContextAttribute(PIPPO_APPLICATION, getApplication());
// add pippo filter
addPippoFilter(info);
// add initializers
info.addListener(new ListenerInfo(PippoServletContextListener.class));
// add listeners
listeners.forEach(listener -> info.addListener(new ListenerInfo(listener)));
ServletInfo defaultServlet = new ServletInfo("DefaultServlet", DefaultServlet.class);
defaultServlet.addMapping("/");
MultipartConfigElement multipartConfig = createMultipartConfigElement();
defaultServlet.setMultipartConfig(multipartConfig);
info.addServlets(defaultServlet);
DeploymentManager deploymentManager = Servlets.defaultContainer().addDeployment(info);
deploymentManager.deploy();
return deploymentManager;
}
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 设置文件大小限制 ,超出设置页面会抛出异常信息,
// 这样在文件上传的地方就需要进行异常信息的处理了;
factory.setMaxFileSize("1024KB"); // KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize("2048KB");
// Sets the directory location where files will be stored.
// factory.setLocation("路径地址");
return factory.createMultipartConfig();
}
public String multiPart(Request baseRequest, HttpServletRequest request, MultipartConfigElement config)
throws Exception {
HttpSession session = request.getSession(false);
String user = (String) session.getAttribute("user");
baseRequest.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, config);
Collection<Part> parts = request.getParts();
for (Part part : parts) {
System.out.println("" + part.getName());
}
Part filePart = request.getPart("file");
InputStream imageStream = filePart.getInputStream();
byte[] resultBuff = new byte[0];
byte[] buff = new byte[1024];
int k = -1;
while ((k = imageStream.read(buff, 0, buff.length)) > -1) {
byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size
// = bytes already
// read + bytes last
// read
System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy
// previous
// bytes
System.arraycopy(buff, 0, tbuff, resultBuff.length, k); // copy
// current
// lot
resultBuff = tbuff; // call the temp buffer as your result buff
}
Map response = new HashMap();
return getString(response);
}