使用SpringBoot上传文件

一、启动类设置

    在启动类中添加

/**
	 * tomcatEmbedded 这段代码是为了解决,上传文件大于10M出现连接重置的问题。
	 * 此异常内容 GlobalException 也捕获不到。
	 * @return
	 */
	@Bean
	public TomcatServletWebServerFactory tomcatEmbedded() {
		TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
		tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
			if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
				// -1 means unlimited
				((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
			}
		});
		return tomcat;
	}

二、页面编写

简单的上传页面编写

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>上传实例</h1>
	<form method="POST" action="/upload" enctype="multipart/form-data">
    	<input type="file" name="file" /><br/><br/>
    	<input type="submit" value="Submit" />
	</form>
</body>
</body>
</html>

结果页面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>上传结果展示:</h1>
	<div th:if="${message}">
		<h2 th:text="${message}" />
	</div>
</body>
</html>

三、上传控制类

@Controller
public class FileController {

	private final String UPLOADED_FOLDER = "H:\\";

	@GetMapping("/")
	public String index() {
		return "upfile";
	}

	@PostMapping("/upload")
	public String singleFileUpload(@RequestParam("file") MultipartFile file, Model model) {

		if (file.isEmpty()) {
			model.addAttribute("message", "没有选择上传文件");
			return "message";
		}

		try {
			// 获取上传文件并保存到指定路径
			byte[] bytes = file.getBytes();
			Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
			Files.write(path, bytes);
			model.addAttribute("message", "成功上传文件: '" + file.getOriginalFilename() + "'");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "message";
	}
}

MultipartFile是Spring上传文件的封装类,包含了文件的二进制流和文件属性等信息,在配置文件中也可对相关属性进行配置,基本的配置信息如下:

#默认支持文件上传.
# spring.http.multipart.enabled=true
#支持文件写入磁盘.
# spring.http.multipart.file-size-threshold=0
# 上传文件的临时目录
# spring.http.multipart.location=
# 最大支持文件大小
spring.http.multipart.max-file-size=1Mb
# 最大支持请求大小
spring.http.multipart.max-request-size=10Mb

测试:

 

四、异常处理

/**
 * MultipartException异常处理器类
 * @author 游王子
 *全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获
 */
@ControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * MultipartException处理方法
	 * @param e
	 * @param redirectAttributes
	 * @return
	 */
	@ExceptionHandler(MultipartException.class)
	public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
		redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
		return "message";
	}
}

关于上传和SpringMVC区别不大,到此就完成springboot上传功能。

发布了71 篇原创文章 · 获赞 2 · 访问量 6168

猜你喜欢

转载自blog.csdn.net/qq_40298351/article/details/102843604