Browse Source

spring-boot-file-upload

纯洁的微笑 7 years ago
parent
commit
03cb1f2c5c

+ 1 - 0
README.md

@@ -23,6 +23,7 @@ Spring boot使用的各种示例,以最简单、最实用为标准
 - [spring-boot-multi-mongodb](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-multi-mongodb):spring boot和mongodb多数据源的使用
 - [spring-boot-multi-mongodb](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-multi-mongodb):spring boot和mongodb多数据源的使用
 - [spring-boot-package-war](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-package-war):spring-boot打包成war包示例
 - [spring-boot-package-war](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-package-war):spring-boot打包成war包示例
 - [spring-boot-shiro](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-shiro):springboot 整合shiro rbac示例
 - [spring-boot-shiro](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-shiro):springboot 整合shiro rbac示例
+- [spring-boot-file-upload](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-file-upload):springboot 集成上传文件示例
 
 
 **[Favorites-web](https://github.com/cloudfavorites/favorites-web):云收藏(springboot实战开源项目)**
 **[Favorites-web](https://github.com/cloudfavorites/favorites-web):云收藏(springboot实战开源项目)**
 
 

+ 4 - 1
README_EN.md

@@ -24,4 +24,7 @@ Spring Boot Examples, Use the simplest and most useful scene demo.
 - [spring-boot-multi-mongodb](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-multi-mongodb):Spring Boot + multiMongodb
 - [spring-boot-multi-mongodb](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-multi-mongodb):Spring Boot + multiMongodb
 - [spring-boot-package-war](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-package-war):Spring Boot package war
 - [spring-boot-package-war](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-package-war):Spring Boot package war
 - [spring-boot-shiro](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-shiro):spring boot shiro rbac demo 
 - [spring-boot-shiro](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-shiro):spring boot shiro rbac demo 
-- [Favorites-web](https://github.com/cloudfavorites/favorites-web):Open source projects developed using Spring Boot
+- [spring-boot-file-upload](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-file-upload):Spring Boot file upload example
+
+
+**[Favorites-web](https://github.com/cloudfavorites/favorites-web):Open source projects developed using Spring Boot**

+ 48 - 0
spring-boot-file-upload/pom.xml

@@ -0,0 +1,48 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
+  http://maven.apache.org/maven-v4_0_0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>com.neo</groupId>
+    <artifactId>spring-boot-file-upload</artifactId>
+    <packaging>jar</packaging>
+    <version>1.0</version>
+
+    <parent>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-parent</artifactId>
+        <version>1.5.7.RELEASE</version>
+    </parent>
+
+    <properties>
+        <java.version>1.8</java.version>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <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>
+
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.springframework.boot</groupId>
+                <artifactId>spring-boot-maven-plugin</artifactId>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

+ 36 - 0
spring-boot-file-upload/src/main/java/com/neo/FileUploadWebApplication.java

@@ -0,0 +1,36 @@
+package com.neo;
+
+import org.apache.coyote.http11.AbstractHttp11Protocol;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
+import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
+import org.springframework.context.annotation.Bean;
+
+@SpringBootApplication
+public class FileUploadWebApplication {
+
+    private int maxUploadSizeInMb = 10 * 1024 * 1024; // 10 MB
+
+    public static void main(String[] args) throws Exception {
+        SpringApplication.run(FileUploadWebApplication.class, args);
+    }
+
+    //Tomcat large file upload connection reset
+    @Bean
+    public TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
+
+        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
+
+        tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
+            if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
+                //-1 means unlimited
+                ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
+            }
+        });
+
+        return tomcat;
+
+    }
+
+}

+ 20 - 0
spring-boot-file-upload/src/main/java/com/neo/controller/GlobalExceptionHandler.java

@@ -0,0 +1,20 @@
+package com.neo.controller;
+
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.multipart.MultipartException;
+import org.springframework.web.servlet.mvc.support.RedirectAttributes;
+
+@ControllerAdvice
+public class GlobalExceptionHandler {
+
+    //https://jira.spring.io/browse/SPR-14651
+    //4.3.5 supports RedirectAttributes redirectAttributes
+    @ExceptionHandler(MultipartException.class)
+    public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
+
+        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
+        return "redirect:/uploadStatus";
+
+    }
+}

+ 57 - 0
spring-boot-file-upload/src/main/java/com/neo/controller/UploadController.java

@@ -0,0 +1,57 @@
+package com.neo.controller;
+
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.multipart.MultipartFile;
+import org.springframework.web.servlet.mvc.support.RedirectAttributes;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+@Controller
+public class UploadController {
+
+    //Save the uploaded file to this folder
+    private static String UPLOADED_FOLDER = "E://temp//";
+
+    @GetMapping("/")
+    public String index() {
+        return "upload";
+    }
+
+    @PostMapping("/upload") // //new annotation since 4.3
+    public String singleFileUpload(@RequestParam("file") MultipartFile file,
+                                   RedirectAttributes redirectAttributes) {
+
+        if (file.isEmpty()) {
+            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
+            return "redirect:uploadStatus";
+        }
+
+        try {
+
+            // Get the file and save it somewhere
+            byte[] bytes = file.getBytes();
+            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
+            Files.write(path, bytes);
+
+            redirectAttributes.addFlashAttribute("message",
+                    "You successfully uploaded '" + file.getOriginalFilename() + "'");
+
+        } catch (IOException e) {
+            e.printStackTrace();
+        }
+
+        return "redirect:/uploadStatus";
+    }
+
+    @GetMapping("/uploadStatus")
+    public String uploadStatus() {
+        return "uploadStatus";
+    }
+
+}

+ 4 - 0
spring-boot-file-upload/src/main/resources/application.properties

@@ -0,0 +1,4 @@
+#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
+#search multipart
+spring.http.multipart.max-file-size=2MB
+spring.http.multipart.max-request-size=10MB

+ 24 - 0
spring-boot-file-upload/src/main/resources/logback.xml

@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<configuration>
+
+    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+        <layout class="ch.qos.logback.classic.PatternLayout">
+            <Pattern>
+                %d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n
+            </Pattern>
+        </layout>
+    </appender>
+
+    <logger name="org.springframework.web" level="error" additivity="false">
+        <appender-ref ref="STDOUT"/>
+    </logger>
+
+    <logger name="com.neo" level="debug" additivity="false">
+        <appender-ref ref="STDOUT"/>
+    </logger>
+
+    <root level="error">
+        <appender-ref ref="STDOUT"/>
+    </root>
+
+</configuration>

+ 13 - 0
spring-boot-file-upload/src/main/resources/templates/upload.html

@@ -0,0 +1,13 @@
+<!DOCTYPE html>
+<html xmlns:th="http://www.thymeleaf.org">
+<body>
+
+<h1>Spring Boot file upload example</h1>
+
+<form method="POST" action="/upload" enctype="multipart/form-data">
+    <input type="file" name="file" /><br/><br/>
+    <input type="submit" value="Submit" />
+</form>
+
+</body>
+</html>

+ 12 - 0
spring-boot-file-upload/src/main/resources/templates/uploadStatus.html

@@ -0,0 +1,12 @@
+<!DOCTYPE html>
+<html lang="en" xmlns:th="http://www.thymeleaf.org">
+<body>
+
+<h1>Spring Boot - Upload Status</h1>
+
+<div th:if="${message}">
+    <h2 th:text="${message}"/>
+</div>
+
+</body>
+</html>