Spring Boot 上传文件(spring boot upload file)

本篇文章将说明在Spring Boot web程序中如何上传文件。

开发环境:

1. eclipse Oxygen Release (4.7.0)

2. Spring Boot 1.4.3 RELEASE

3. Spring 4.3.5 RELEASE

4. Thymelaef

5. Maven

6. Embedded Tomcat 8


1.最终的项目结构

Spring Boot 上传文件(spring boot upload file)_第1张图片

2.项目所需依赖 pom.xml


  4.0.0

  org.thinkingingis
  spring-boot-fileupload
  0.0.1-SNAPSHOT
  jar

  spring-boot-fileupload
  http://maven.apache.org

    
        org.springframework.boot
        spring-boot-starter-parent
        1.4.3.RELEASE
    

  
    1.8
  

  
  
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-devtools
            true
        

  
  
  
  
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    
  


3. UploadController.java

用MultipartFile类去匹配上传的文件

package org.thinkingingis.controller;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

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;

@Controller
public class UploadController {
	
	private static String UPLOAD_FOLDER = "H://temp//";
	
	@GetMapping("/")
	public String index() {
		return "upload";
	}
	
	@PostMapping("/upload")
	public String singleFileUpload(@RequestParam("file") MultipartFile file,
								   RedirectAttributes redirectAttributes) {
		if(file.isEmpty()) {
			redirectAttributes.addFlashAttribute("message", "请选择一个上传文件");
		}
		
		try {
			
			byte[] bytes = file.getBytes();
			Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename());
			Files.write(path, bytes);
			redirectAttributes.addFlashAttribute("message", "已经将 '" + file.getOriginalFilename() + "' 的文件上传成功");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "redirect:/uploadStatus";
	}
	
	@GetMapping("/uploadStatus")
	public String uploadStatus() {
		return "uploadStatus";
	}
	
}

4. Thymeleaf 前端页面

4.1 upload.html





	  




ThinkingInGIS


Spring Boot 文件上传示例



4.2  uploadStatus.html





	  




Spring Boot - 上传状态

5. 处理文件过大的情况

下面 GlobalExceptionHandler.java 这个类是处理当上传文件超过10mb限制所引发的异常情况。

package org.thinkingingis.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@ControllerAdvice
public class GlobalExceptionHandler {
	
	public String handerError(MultipartException e, RedirectAttributes redirectAttributes) {
		redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
		return "redirect:/uploadStatus";
	}

}

6. Tomcat大文件重置连接

对于embedded tomcat ,需要声明TomcatEmbeddedServletContainerFactory

package org.thinkingingis.controller;

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 SpringBootWebApplication {
	
	//private int maxUploadFileSize = 10 * 1024 * 1024;
	
	public static void main(String[] args) throws Exception {
		SpringApplication.run(SpringBootWebApplication.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;
    }
}


7. 在application.properties中设置上传文件的上限

#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
#search multipart
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=10MB


8. 进入项目文件  输入 mvn spring-boot:run
Spring Boot 上传文件(spring boot upload file)_第2张图片

9. 启动成功后浏览器输入 localhost:8080

Spring Boot 上传文件(spring boot upload file)_第3张图片

上传成功后

Spring Boot 上传文件(spring boot upload file)_第4张图片


到此就实现了Spring Boot上传文件的功能。

如遇到问题,欢迎通过公众号留言给作者,以便共同探讨。

邮箱:[email protected]

微信公众号:

Spring Boot 上传文件(spring boot upload file)_第5张图片

你可能感兴趣的:(spring,boot)