SpringBoot文件上传
https://blog.csdn.net/cx243698/article/details/80234444
我们在工作中经常会遇到文件上传的需求,本文使用SpringBoot简单实现文件上传。
首先Pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- thmleaf模板依赖. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
编写Controller层
@Controller
public class FileUploadController {
private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
/**
* 跳转到单个文件上传
*
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public ModelAndView upload() {
return new ModelAndView("/fileUpload");
}
/**
* 跳转到多个文件上传
*
* @return
*/
@RequestMapping(value = "/upload/batch", method = RequestMethod.GET)
public ModelAndView batchUpload() {
return new ModelAndView("/multiFileUpload");
}
/**
* 文件上传具体实现方法(单文件上传)
*
* @param file
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
logger.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("文件的后缀名为:" + suffixName);
// 设置文件存储路径
String filePath = "E://xuchen//";
String path = filePath + fileName + suffixName;
File dest = new File(path);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夹
}
file.transferTo(dest);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
/**
* 多文件上传
*
* @param request
* @return
*/
@RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
@ResponseBody
public String batchUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file;
BufferedOutputStream stream;
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
stream.write(bytes);
stream.close();
} catch (Exception e) {
stream = null;
return "文件上传失败 " + i + " => " + e.getMessage();
}
} else {
return "文件上传失败 " + i + "原因:上传文件为空!";
}
}
return "文件上传成功";
}
}
文件上传相关配置
@Configuration
public class FileUploadConfiguration {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 设置文件大小限制 ,超出设置页面会抛出异常信息,
// 这样在文件上传的地方就需要进行异常信息的处理了;
factory.setMaxFileSize("2MB");
/// 设置总上传数据总大小
factory.setMaxRequestSize("5MB");
return factory.createMultipartConfig();
}
}
前端页面(单个上传)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>单个文件上传</title>
</head>
<body>
<h2>文件上传示例</h2>
<hr/>
<form method="POST" enctype="multipart/form-data" action="/upload">
<p>
文件:<input type="file" name="file"/>
</p>
<p>
<input type="submit" value="上传"/>
</p>
</form>
</body>
</html>
测试结果
Demo源码下载地址:https://gitee.com/inchlifc/SpringBootTest.git