1.前后端不分离:
springboot项目中static目录下新建upload.html(导入thymeleaf依赖)
可以对上传的文件进行配置:
#设置单个文件上传大小
spring.servlet.multipart.max-file-size=10MB
# 设置总上传文件大小
spring.servlet.multipart.max-request-size=100MB
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
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="uploadFile" value="选择文件">
<input type="submit" value="上传">
</form>
</body>
</html>
controller:
@PostMapping("/upload")
public String upload(MultipartFile uploadFile,HttpServletRequest req)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/");
String format = sdf.format(new Date());
File folder = new File(realPath + format);
if(!folder.isDirectory())
folder.mkdirs();
String oldName = uploadFile.getOriginalFilename();
String newName = "nice" + oldName.substring(oldName.lastIndexOf("."),oldName.length());
try{
uploadFile.transferTo(new File(folder,newName));
String filePath =
req.getScheme() + "://" + req.getServerName() +":"+req.getServerPort()+
"/uploadFile/" + format+newName;
return filePath;
}
catch (IOException e)
{
e.printStackTrace();
}
return "上传失败";
}
然后输入地址:
选择图片点击上传后:
然后浏览器输入:
同时可以在html中用img标签访问,输入上面的url也可以访问到