SpringBoot:文件上传、静态资源拦截、JSON转换
文件上传
在application.properties进行文件上传信息的配置
#上传单个文件的大小
spring.servlet.multipart.max-file-size=1MB
#上传文件的总大小
spring.servlet.multipart.max-request-size=20MB
#文件上传临界值,超过这个临界值,保存到location
spring.servlet.multipart.file-size-threshold=10KB
#文件上传临时保存目录
spring.servlet.multipart.location=
在这里插入代码片在Controller里面添加代码
@RequestMapping("goupload")
public String goupload(Model model){
return "fileupload";
}
@RequestMapping("upload")
public String inupload(MultipartFile file, HttpServletRequest req) throws IOException {
SimpleDateFormat sdf=new SimpleDateFormat("/yyyy/MM/dd/");
String format=sdf.format(new Date());
//创建保存路径
String realpath=req.getServletContext().getRealPath("/img")+format;
File files=new File(realpath);
if(!files.exists()){
files.mkdirs();//如果没有,则创建
}
String oldname=file.getOriginalFilename();
String newname= UUID.randomUUID().toString()+oldname.substring(oldname.lastIndexOf("."),oldname.length());
file.transferTo(new File(files,newname));
//配置请求路径
//req.getScheme()->获取请求协议;
String url=req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/img"+format+newname;
System.out.println(url);
//重定向到goupload页面
return "redirect:/goupload";
}
创建jsp页面
jsp的内容为
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传页面</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data" >
<input type="file" name="file">
<input type="submit" value="文件上传">
</form>
</body>
</html>
测试
http://localhost:8080/goupload
JSON转换
接收传瑞的对象数据
使用@RequestBody接收
在controler里面
@RequestMapping("/typejson")
@ResponseBody
public Book_type typejson(@RequestBody Book_type book_type){
System.out.println(book_type.getType_name()+"****");
return book_type;
}
使用Postman进行测试
传入数据
后台可以接收到数据
HttpServletRequest接收
@PostMapping("/typejsonother")
@ResponseBody
public Book_type typejsonother(HttpServletRequest req) throws IOException {
ServletInputStream is=req.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String s=br.readLine();
Book_type book_type=new ObjectMapper().readValue(s,Book_type.class);
System.out.println(book_type.getType_name()+"****");
return book_type;
}