单文件上传
package com.hang.controller;
import org.springframework.http.HttpRequest;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@Controller
public class OneUpController {
@GetMapping("/tOneFileUp")
public String toOnFileUp(){
return "OneFileUp";
}
@PostMapping("upload")
@ResponseBody
public String upLoad(@RequestParam("file") MultipartFile file, HttpServletRequest request){
if(file.isEmpty()){
return "上传失败";
}
String fileName = file.getOriginalFilename();
//上传到本地
//String filePath = "D:/img/";
//上传至服务器
String filePath = request.getSession().getServletContext().getRealPath("img/");
File up = new File(filePath + fileName);
try {
file.transferTo(up);
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
#上传文件总大小
spring:
servlet:
multipart:
max-request-size: 10MB
max-file-size: 10MB #单个文件上传总大小
thymeleaf:
prefix: classpath:/templates/
suffix: .html
resources:
static-locations: classpath:/static/ #文件静态资源存放路径
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>单文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
</body>
</html>