SpringBoot:文件上传、JSON转换

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;
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值