springmvc上传文件实现 JAVA
异常:上传文件大小超出上限
org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException
解决方法:在配置文件中加入下面两行配置
// 设置单个文件大小
spring.servlet.multipart.max-file-size= 50MB
// 设置单次请求文件的总大小
spring.servlet.multipart.max-request-size= 50MB
1、单个文件上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
@RestController
@RequestMapping("file")
public class FileController {
@PostMapping("upload")
public String saveFile(@RequestParam("file") MultipartFile file, HttpServletRequest request){
try {
File file1 = new File("d:/java/timg1.txt");
file.transferTo(file1);
}catch (Exception e){
e.printStackTrace();
}
return "上传成功!";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="file" name="file2">
<input type="submit" value="上传">
</form>
</body>
</html>
2、多个文件上传
@RestController
@RequestMapping("file")
public class FileController {
@PostMapping("upload")
public String saveFile(MultipartFile file, MultipartFile file2, HttpServletRequest request){
try {
File f1 = new File("d:/java/timg5.jpg");
File f2 = new File("d:/java/timg6.jpg");
file.transferTo(f1);
file2.transferTo(f2);
}catch (Exception e){
e.printStackTrace();
}
return "上传成功!";
}
}
当服务器端controller中接收数据的变量名与前端提交数据的变量名相同时@requestParam注解可以省略