Skip to content

Commit 8d398b2

Browse files
committed
Add file upload example
1 parent 925f174 commit 8d398b2

8 files changed

Lines changed: 296 additions & 115 deletions

File tree

‎spring-mvc-java/.classpath‎

Lines changed: 37 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,37 @@
1-
<?xml version="1.0" encoding="UTF-8"?>
2-
<classpath>
3-
<classpathentry kind="src" output="target/classes" path="src/main/java">
4-
<attributes>
5-
<attribute name="optional" value="true"/>
6-
<attribute name="maven.pomderived" value="true"/>
7-
</attributes>
8-
</classpathentry>
9-
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
10-
<attributes>
11-
<attribute name="optional" value="true"/>
12-
<attribute name="maven.pomderived" value="true"/>
13-
</attributes>
14-
</classpathentry>
15-
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
16-
<attributes>
17-
<attribute name="maven.pomderived" value="true"/>
18-
</attributes>
19-
</classpathentry>
20-
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
21-
<attributes>
22-
<attribute name="maven.pomderived" value="true"/>
23-
</attributes>
24-
</classpathentry>
25-
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
26-
<attributes>
27-
<attribute name="maven.pomderived" value="true"/>
28-
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
29-
</attributes>
30-
</classpathentry>
31-
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
32-
<attributes>
33-
<attribute name="maven.pomderived" value="true"/>
34-
</attributes>
35-
</classpathentry>
36-
<classpathentry kind="output" path="target/classes"/>
37-
</classpath>
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<classpath>
3+
<classpathentry kind="src" output="target/classes" path="src/main/java">
4+
<attributes>
5+
<attribute name="optional" value="true"/>
6+
<attribute name="maven.pomderived" value="true"/>
7+
</attributes>
8+
</classpathentry>
9+
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
10+
<attributes>
11+
<attribute name="optional" value="true"/>
12+
<attribute name="maven.pomderived" value="true"/>
13+
</attributes>
14+
</classpathentry>
15+
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
16+
<attributes>
17+
<attribute name="maven.pomderived" value="true"/>
18+
</attributes>
19+
</classpathentry>
20+
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
21+
<attributes>
22+
<attribute name="maven.pomderived" value="true"/>
23+
</attributes>
24+
</classpathentry>
25+
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
26+
<attributes>
27+
<attribute name="maven.pomderived" value="true"/>
28+
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
29+
</attributes>
30+
</classpathentry>
31+
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
32+
<attributes>
33+
<attribute name="maven.pomderived" value="true"/>
34+
</attributes>
35+
</classpathentry>
36+
<classpathentry kind="output" path="target/classes"/>
37+
</classpath>

‎spring-mvc-java/pom.xml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,13 @@
5757
<artifactId>slf4j-log4j12</artifactId>
5858
<version>${org.slf4j.version}</version>
5959
</dependency>
60+
<!-- common -->
61+
<dependency>
62+
<groupId>commons-fileupload</groupId>
63+
<artifactId>commons-fileupload</artifactId>
64+
<version>1.3.1</version>
65+
</dependency>
66+
6067
<!-- test scoped -->
6168
<dependency>
6269
<groupId>junit</groupId>

‎spring-mvc-java/src/main/java/org/baeldung/spring/web/config/ClientWebConfig.java‎

Lines changed: 57 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -25,69 +25,71 @@
2525
@Configuration
2626
public class ClientWebConfig extends WebMvcConfigurerAdapter {
2727

28-
public ClientWebConfig() {
29-
super();
30-
}
28+
public ClientWebConfig() {
29+
super();
30+
}
3131

32-
// API
32+
// API
3333

34-
@Override
35-
public void addViewControllers(final ViewControllerRegistry registry) {
36-
super.addViewControllers(registry);
34+
@Override
35+
public void addViewControllers(final ViewControllerRegistry registry) {
36+
super.addViewControllers(registry);
3737

38-
registry.addViewController("/sample.html");
39-
}
38+
registry.addViewController("/sample.html");
39+
registry.addViewController("/fileUpload.html");
40+
registry.addViewController("/fileUploadForm.html");
41+
}
4042

41-
@Bean
42-
public ViewResolver thymeleafViewResolver() {
43-
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
44-
viewResolver.setTemplateEngine(templateEngine());
45-
viewResolver.setOrder(1);
46-
return viewResolver;
47-
}
43+
@Bean
44+
public ViewResolver thymeleafViewResolver() {
45+
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
46+
viewResolver.setTemplateEngine(templateEngine());
47+
viewResolver.setOrder(1);
48+
return viewResolver;
49+
}
4850

49-
@Bean
50-
public ViewResolver viewResolver() {
51-
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
52-
bean.setViewClass(JstlView.class);
53-
bean.setPrefix("/WEB-INF/view/");
54-
bean.setSuffix(".jsp");
55-
bean.setOrder(0);
56-
return bean;
57-
}
51+
@Bean
52+
public ViewResolver viewResolver() {
53+
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
54+
bean.setViewClass(JstlView.class);
55+
bean.setPrefix("/WEB-INF/view/");
56+
bean.setSuffix(".jsp");
57+
bean.setOrder(0);
58+
return bean;
59+
}
5860

59-
@Bean
60-
@Description("Thymeleaf template resolver serving HTML 5")
61-
public ServletContextTemplateResolver templateResolver() {
62-
final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
63-
templateResolver.setPrefix("/WEB-INF/templates/");
64-
templateResolver.setSuffix(".html");
65-
templateResolver.setTemplateMode("HTML5");
66-
return templateResolver;
67-
}
61+
@Bean
62+
@Description("Thymeleaf template resolver serving HTML 5")
63+
public ServletContextTemplateResolver templateResolver() {
64+
final ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
65+
templateResolver.setPrefix("/WEB-INF/templates/");
66+
templateResolver.setSuffix(".html");
67+
templateResolver.setTemplateMode("HTML5");
68+
return templateResolver;
69+
}
6870

69-
@Bean
70-
@Description("Thymeleaf template engine with Spring integration")
71-
public SpringTemplateEngine templateEngine() {
72-
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
73-
templateEngine.setTemplateResolver(templateResolver());
74-
final Set<IDialect> dialects = new HashSet<>();
75-
dialects.add(new CustomDialect());
76-
templateEngine.setAdditionalDialects(dialects);
77-
return templateEngine;
78-
}
71+
@Bean
72+
@Description("Thymeleaf template engine with Spring integration")
73+
public SpringTemplateEngine templateEngine() {
74+
final SpringTemplateEngine templateEngine = new SpringTemplateEngine();
75+
templateEngine.setTemplateResolver(templateResolver());
76+
final Set<IDialect> dialects = new HashSet<>();
77+
dialects.add(new CustomDialect());
78+
templateEngine.setAdditionalDialects(dialects);
79+
return templateEngine;
80+
}
7981

80-
@Bean
81-
@Description("Spring message resolver")
82-
public MessageSource messageSource() {
83-
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
84-
messageSource.setBasename("messages");
85-
return messageSource;
86-
}
82+
@Bean
83+
@Description("Spring message resolver")
84+
public MessageSource messageSource() {
85+
final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
86+
messageSource.setBasename("messages");
87+
return messageSource;
88+
}
8789

88-
@Override
89-
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
90-
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
91-
}
90+
@Override
91+
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
92+
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
93+
}
9294

9395
}

‎spring-mvc-java/src/main/java/org/baeldung/spring/web/config/MainWebAppInitializer.java‎

Lines changed: 33 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,28 +14,38 @@
1414

1515
public class MainWebAppInitializer implements WebApplicationInitializer {
1616

17-
/**
18-
* Register and configure all Servlet container components necessary to power the web application.
19-
*/
20-
@Override
21-
public void onStartup(final ServletContext sc) throws ServletException {
22-
System.out.println("MainWebAppInitializer.onStartup()");
23-
24-
// Create the 'root' Spring application context
25-
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
26-
root.scan("org.baeldung.spring.web.config");
27-
// root.getEnvironment().setDefaultProfiles("embedded");
28-
29-
// Manages the lifecycle of the root application context
30-
sc.addListener(new ContextLoaderListener(root));
31-
32-
// Handles requests into the application
33-
final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
34-
appServlet.setLoadOnStartup(1);
35-
final Set<String> mappingConflicts = appServlet.addMapping("/");
36-
if (!mappingConflicts.isEmpty()) {
37-
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
38-
}
39-
}
17+
private static final String TMP_FOLDER = "C:/Users/ivan/Desktop/tmp"; // 5
18+
// MB
19+
private static final int MAX_UPLOAD_SIZE = 5 * 1024 * 1024; // 5 MB
20+
21+
/**
22+
* Register and configure all Servlet container components necessary to power the web application.
23+
*/
24+
@Override
25+
public void onStartup(final ServletContext sc) throws ServletException {
26+
27+
// Create the 'root' Spring application context
28+
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
29+
root.scan("org.baeldung.spring.web.config");
30+
// root.getEnvironment().setDefaultProfiles("embedded");
31+
32+
// Manages the lifecycle of the root application context
33+
sc.addListener(new ContextLoaderListener(root));
34+
35+
// Handles requests into the application
36+
final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
37+
appServlet.setLoadOnStartup(1);
38+
39+
// final MultipartConfigElement multipartConfigElement = new
40+
// MultipartConfigElement(TMP_FOLDER, MAX_UPLOAD_SIZE,
41+
// MAX_UPLOAD_SIZE * 2, MAX_UPLOAD_SIZE / 2);
42+
//
43+
// appServlet.setMultipartConfig(multipartConfigElement);
44+
45+
final Set<String> mappingConflicts = appServlet.addMapping("/");
46+
if (!mappingConflicts.isEmpty()) {
47+
throw new IllegalStateException("'appServlet' could not be mapped to '/' due " + "to an existing mapping. This is a known issue under Tomcat versions " + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278");
48+
}
49+
}
4050

4151
}

‎spring-mvc-java/src/main/java/org/baeldung/spring/web/config/WebConfig.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,21 @@ public WebConfig() {
2222
super();
2323
}
2424

25+
// @Bean
26+
// public StandardServletMultipartResolver multipartResolver() {
27+
// return new StandardServletMultipartResolver();
28+
// }
29+
30+
// @Bean(name = "multipartResolver")
31+
// public CommonsMultipartResolver multipartResolver() {
32+
//
33+
// final CommonsMultipartResolver multipartResolver = new
34+
// CommonsMultipartResolver();
35+
// multipartResolver.setMaxUploadSize(100000);
36+
//
37+
// return multipartResolver;
38+
// }
39+
2540
@Override
2641
public void addViewControllers(final ViewControllerRegistry registry) {
2742

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package org.baeldung.web.controller;
2+
3+
import java.io.File;
4+
import java.io.IOException;
5+
import java.util.Iterator;
6+
import java.util.List;
7+
8+
import javax.servlet.http.HttpServletRequest;
9+
import javax.servlet.http.HttpServletResponse;
10+
11+
import org.apache.commons.fileupload.FileItem;
12+
import org.apache.commons.fileupload.FileUploadException;
13+
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
14+
import org.apache.commons.fileupload.servlet.ServletFileUpload;
15+
import org.apache.commons.io.FileUtils;
16+
import org.springframework.stereotype.Controller;
17+
import org.springframework.ui.ModelMap;
18+
import org.springframework.web.bind.annotation.RequestMapping;
19+
import org.springframework.web.bind.annotation.RequestMethod;
20+
import org.springframework.web.bind.annotation.RequestParam;
21+
import org.springframework.web.multipart.MultipartFile;
22+
23+
@Controller
24+
public class FileUploadController {
25+
26+
@RequestMapping(value = "/addFile1", method = RequestMethod.POST)
27+
public String submit(@RequestParam("file") final MultipartFile file, final ModelMap modelMap) {
28+
29+
modelMap.addAttribute("fileName", file.getOriginalFilename());
30+
modelMap.addAttribute("fileType", file.getContentType());
31+
32+
return "fileUploadView";
33+
}
34+
35+
@RequestMapping(value = "/addFile2", method = RequestMethod.POST)
36+
public String submit(final HttpServletRequest request, final HttpServletResponse response,
37+
final ModelMap modelMap) {
38+
39+
final String TEMP_PATH = "C:\\Users\\ivan\\Desktop\\tmp\\";
40+
41+
try {
42+
43+
final DiskFileItemFactory factory = new DiskFileItemFactory();
44+
45+
// Configure a repository (to ensure a secure temp location is used)
46+
final File repository = new File(TEMP_PATH);
47+
factory.setRepository(repository);
48+
49+
// Create a new file upload handler
50+
final ServletFileUpload upload = new ServletFileUpload(factory);
51+
52+
// Parse the request
53+
final List<FileItem> items = upload.parseRequest(request);
54+
55+
final Iterator<FileItem> iter = items.iterator();
56+
57+
while (iter.hasNext()) {
58+
59+
final FileItem item = iter.next();
60+
61+
if (!item.isFormField()) {
62+
63+
final File targetFile = new File(TEMP_PATH + item.getName());
64+
FileUtils.copyInputStreamToFile(item.getInputStream(), targetFile);
65+
66+
modelMap.addAttribute("fileName", item.getName());
67+
modelMap.addAttribute("fileType", item.getContentType());
68+
}
69+
}
70+
71+
} catch (final FileUploadException e) {
72+
e.printStackTrace();
73+
74+
} catch (final IOException e) {
75+
e.printStackTrace();
76+
}
77+
78+
return "fileUploadView";
79+
}
80+
}

0 commit comments

Comments
 (0)