springboot上传文件
springboot上传单个文件
controller
@RestController
public class UploadController {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest req){
String format = sdf.format(new Date());
String realPath = req.getServletContext().getRealPath("/img/")+ format;
File folder = new File(realPath);
if(!folder.exists()){
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(folder,newName));
String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/img/"+format+"/"+newName;
return url;
} catch (IOException e) {
e.printStackTrace();
}
return "error";
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" name="tijiao">
</form>
</body>
</html>