Spring框架
Jdk 1.8+
Eclipse开发工具
Maven 3.0
第一步、在eclipse中构建一个标准的Maven工程工程的信息:
为工程添加Spring MVC和Spring boot相关的依赖
创建文件存储服务的接口和实现类,对处理WEB页面的文件上传服务1)文件存储服务接口类:StorageService.javaimport org.springframework.core.io.Resource;import org.springframework.web.multipart.MultipartFile;import java.nio.file.Path;import java.util.stream.Stream;public interface StorageService { void init(); void store(MultipartFile file); Stream
创建一个文件存储属性配置类,实现文件存储的相关自定义属性配置,如文件上传的目录名称: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; }}
实现文件上传控制器,这个是整个WEB应用的的核心,实现WEB页面到文件存储服务的联接控制。文件名:FileUploadController.javapackage image;import java.io.IOException;import java.util.stream.Collectors;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.core.io.Resource;import org.springframework.http.ResponseEntity;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;import org.springframework.web.servlet.mvc.support.RedirectAttributes;import image.storage.StorageFileNotFoundException;import image.storage.StorageService;/** * 文件上传服务控制器 * @author Fantasy * */@Controllerpublic class FileUploadController { private final StorageService storageService; @Autowired public FileUploadController(StorageService storageService) { this.storageService = storageService; } //文件上传的url入口:/upload,然后转入templates目录下的uploadForm.html文件 @GetMapping('/upload') public String showUploadPage(Model model) throws IOException { return 'uploadForm'; } //处理post上传文件的url:/upload,处理成功后页面跳转掉“/result” @PostMapping('/upload') public String handleFileUpload(@RequestParam('file') MultipartFile file, RedirectAttributes redirectAttributes) { storageService.store(file); redirectAttributes.addFlashAttribute('message', '文件: ' + file.getOriginalFilename() + '上传成功!'); return 'redirect:/result'; } //处理url:/result的请求,显示templates目录下的uploadResult.html文件 //显示上传的文件列表 @GetMapping('/result') public String listUploadedFiles(Model model) throws IOException { model.addAttribute('files', storageService.loadAll().map( path -> MvcUriComponentsBuilder.fromMethodName(FileUploadController.class, 'serveFile', path.getFileName().toString()).build().toString()) .collect(Collectors.toList())); System.out.println(model); return 'uploadResult'; } //查看已经上传的文件 @GetMapping('/files/{filename:.+}') @ResponseBody public ResponseEntity
为页面创建静态资源目录,存储静态的html、js,css、图片等文件如在项目中需要用的jquery则需要将jquery的库文件放在工程的静态目录中:E:\workspace\image\src\main\resources\static\js\jquery-3.2.1.min.js在这个工程中我们将index.html和jquery-3.2.1.min.js放在静态文件目录下。
为Spring MVC提供thymeleaf模板的WEB页面文件,提供文件上传的页面和文件展现的页面;1)文件上传页面:该页面展示了如何引用静态js文件uploadForm.html
为Spring应用设置相关的属性,如文件上传的大小,避免出现大坑在resources目录下创建spring的属性配置文件application.propertiesspring.http.multipart.max-file-size=128MBspring.http.multipart.max-request-size=128MB
最后创建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(); }; }}
运行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
在浏览器中进行测试web应用,推荐使用chrome或极速浏览器,windows 10的edge浏览器不支持的