本篇文章主要介绍在Springboot中如何上传文件
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
上传页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="/upload">
<table>
<tr><td><input type="file" name="file" /></td></tr>
<tr><td><input type="submit" value="上传" /></td></tr>
</table>
</form>
</body>
</html>
application.properties配置文件
#限制请求上传单个文件大小
spring.servlet.multipart.max-file-size=5KB
#限制请求上传总文件大小
spring.servlet.multipart.max-request-size=5KB
#spring.http.multipart.max-file-size=5KB 老版本
#spring.http.multipart.max-request-size= 5KB 老版本
Controller类
package com.example.springboot_uploadfile.controller;
import ch.qos.logback.core.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
/**
* @author XuJD
* @create 2018-11-01 18:02
**/
@Controller
public class IndexController {
@RequestMapping("/index")
public String index(){
return "index";
}
@ResponseBody
@RequestMapping("/upload")
public String upload(@RequestParam("file")MultipartFile file, HttpServletRequest request){
String fileName = file.getOriginalFilename();
try {
//文件上传到目标地址
String filePath = "G:\\demo\\fileUpload\\";
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file.getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return "上传成功";
}
}
测试
上传一个超过5KB大小的文件试试,可以发现会报如下错误
示例代码下载-github:https://github.com/xujiangdong/SpringbootLearn