Spring MVC/Spring Boot实现图片文件上传和显示
1、第一步、在eclipse中构建一个标准的Maven工程工程的信息: <groupId>fantasy</groupId> <artifactId>image</artifactId>

2、为工程添加Spring MVC和Spring boot相关的依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>

4、创建一个文件存储属性配置类,实现文件存储的相关自定义属性配置,如文件上传的目录名称:StorageProperties.java该类指定了文件上传的目录位置为:upload-dirpackage image.storage;import org.springframework.boot.context.properties.ConfigurationProperties;@ConfigurationProperties("storage")public class StorageProperties { /** * Folder location for storing files */ private String location = "upload-dir"; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; }}

7、为Spring MVC提供thymeleaf模板的WEB页面文件,提供文件上传的页面和文件展现的页面;1)文件上传页面:该页面展示了如何引用静态js文件uploadForm.html<html xmlns:th="http://www.thymeleaf.org"><head><!-- 静态文件css,js等放在static目录下 --><script src="./js/jquery-3.2.1.min.js"></script><script>$(document).ready(function(){ alert("Upload File Page");});</script></head><body> <div> <form method="POST" enctype="multipart/form-data" action="/upload"> <table> <tr><td>File to upload:</td><td><input type="file" name="file" accept="image/*"/></td></tr> <tr><td></td><td><input type="submit" value="Upload" /></td></tr> </table> </form> </div></body></html>2)文件上传结果展示页面:uploadResult.html注意:上传的文件是图片文件时才可以在页面上正常显示的<html xmlns:th="http://www.thymeleaf.org"><body> <div th:if="${message}"> <h2 th:text="${message}"/> </div> <div> <ul> <li th:each="file : ${files}"> <img th:src="${file}"/> <a th:href="${file}" th:text="${file}" /> </li> </ul> </div></body></html>

9、最后创建Spring boot的应用程序入口Application.javapackage image;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Bean;import image.storage.StorageProperties;import image.storage.StorageService;@SpringBootApplication@EnableConfigurationProperties(StorageProperties.class)public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean CommandLineRunner init(StorageService storageService) { return (args)->{ storageService.deleteAll(); storageService.init(); }; }}
10、运行application.java类,启动spring boot应用10:53:55.672 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []10:53:55.674 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]10:53:55.674 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/E:/workspace/image/target/classes/] . ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v1.5.9.RELEASE)2018-01-07 10:53:55.950 INFO 2932 --- [ restartedMain] image.Application : Starting Application on V3EQ67T1ANYZUSN with PID 2932 (E:\workspace\image\target\classes started by Administrator in E:\workspace\image)2018-01-07 10:53:55.950 INFO 2932 --- [ restartedMain] image.Application : No active profile set, falling back to default profiles: default2018-01-07 10:53:56.193 INFO 2932 --- [ restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1f8de44: startup date [Sun Jan 07 10:53:56 CST 2018]; root of context hierarchy2018-01-07 10:53:57.719 INFO 2932 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)2018-01-07 10:53:57.734 INFO 2932 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]2018-01-07 10:53:57.736 INFO 2932 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.232018-01-07 10:53:57.862 INFO 2932 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext2018-01-07 10:53:57.862 INFO 2932 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1670 ms2018-01-07 10:53:58.020 INFO 2932 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]2018-01-07 10:53:58.025 INFO 2932 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]2018-01-07 10:53:58.025 INFO 2932 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]2018-01-07 10:53:58.026 INFO 2932 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]2018-01-07 10:53:58.026 INFO 2932 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]2018-01-07 10:53:58.361 INFO 2932 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1f8de44: startup date [Sun Jan 07 10:53:56 CST 2018]; root of context hierarchy2018-01-07 10:53:58.435 INFO 2932 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/img/{filename:.+}],methods=[GET]}" onto public org.springframework.http.ResponseEntity<org.springframework.core.io.Resource> image.FileUploadController.getFile(java.lang.String)2018-01-07 10:53:58.436 INFO 2932 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/upload],methods=[GET]}" onto public java.lang.String image.FileUploadController.showUploadPage(org.springframework.ui.Model) throws java.io.IOException2018-01-07 10:53:58.440 INFO 2932 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/upload],methods=[POST]}" onto public java.lang.String image.FileUploadController.handleFileUpload(org.springframework.web.multipart.MultipartFile,org.springframework.web.servlet.mvc.support.RedirectAttributes)2018-01-07 10:53:58.440 INFO 2932 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/files/{filename:.+}],methods=[GET]}" onto public org.springframework.http.ResponseEntity<org.springframework.core.io.Resource> image.FileUploadController.serveFile(java.lang.String)2018-01-07 10:53:58.441 INFO 2932 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/result],methods=[GET]}" onto public java.lang.String image.FileUploadController.listUploadedFiles(org.springframework.ui.Model) throws java.io.IOException2018-01-07 10:53:58.443 INFO 2932 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)2018-01-07 10:53:58.443 INFO 2932 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)2018-01-07 10:53:58.473 INFO 2932 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2018-01-07 10:53:58.473 INFO 2932 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2018-01-07 10:53:58.516 INFO 2932 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]2018-01-07 10:53:59.020 INFO 2932 --- [ restartedMain] oConfiguration$WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]2018-01-07 10:53:59.241 INFO 2932 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 357292018-01-07 10:53:59.328 INFO 2932 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup2018-01-07 10:53:59.419 INFO 2932 --- [ restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)2018-01-07 10:53:59.426 INFO 2932 --- [ restartedMain] image.Application : Started Application in 3.737 seconds (JVM running for 4.758)

