文件上传和JSON数据概述

这篇博客介绍了Java Spring后端开发中的文件上传和JSON数据处理。在文件上传部分,详细讲解了多文件上传的实现,包括表单和控制器的设置。在JSON部分,阐述了JSON作为数据交换格式的特点,如轻量级、语言无关,并给出了入门案例,展示了如何在Spring MVC中使用Jackson进行JSON数据的接收和响应,包括@RequestBody和@ResponseBody注解的运用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.文件上传

2.1 多文件上传

  • 表单

        <form action="${pageContext.request.contextPath}/file/upload2.action" method="post" enctype="multipart/form-data">
          选择文件: <input type="file" name="images" /> <br/>
          选择文件: <input type="file" name="images" /> <br/>
          选择文件: <input type="file" name="images" /> <br/>
          <input type="submit" value="上传"/> <br/>
        </form>
    
  • 控制器

        @RequestMapping("/upload2")
        public String upload2(List<MultipartFile> images) throws Exception {
            for (MultipartFile image : images) {
                System.out.println("上传文件名:" + image.getOriginalFilename());
                System.out.println("上传文件流:" + image.getInputStream());
    
                File file = new File("D:\\xml", image.getOriginalFilename());
                FileUtils.copyInputStreamToFile(image.getInputStream(), file );
            }
            return "book";
        }
    

3. JSON

3.1 JSON 使用流程分析

3.2 JSON数据

  • 什么是JSON数据?

    • 是一种轻量级的数据交换格式。
    • 轻量级,不依赖任何框架,任何语言。
  • 数据分类:对象、数组

    • 对象

      • key必须使用双引号
      • value除特殊类型外,都需要使用双引号。(特殊类型:数字、布尔true/false)
      {
          "k":"v",
          "k2":"v2",....
      }
      
    • 数组

      [
      	元素,元素2,....
      ]
      

3.3 入门案例

3.3.1 目标

  • 目标:请求JSON数据,响应JSON数据
  • 案例:用户条件查询,
    • 请求:查询条件 User
    • 响应:查询结果 List<User>
  • 前提:spring mvc 底层 jackson 处理json数据。

3.3.2 步骤

  • 步骤:
    1. 导入 jackson 相关的jar包
    2. 编写JavaBean:User
    3. 编写controller,接收请求数据 @RequestBody
    4. 编写controller,响应数据 @ResponseBody
    5. postman测试

3.3.3 实现

  • 导入 jackson 相关的jar包

在这里插入图片描述

  • 编写JavaBean:User

    package com.czxy.mvcanno.domain;
    
    import org.springframework.format.annotation.DateTimeFormat;
    
    import java.util.Date;
    import java.util.List;
    
    
    public class User {
        private Integer id;
        private String username;
        private String password;
      
        public User() {
        }
    
        public User(Integer id, String username, String password) {
            this.id = id;
            this.username = username;
            this.password = password;
        }
        // getter和setter
    }
    
    
  • 编写controller,接收请求数据 @RequestBody

    package com.czxy.mvcanno.controller;
    
    import com.czxy.mvcanno.domain.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    
    @Controller
    @RequestMapping("/json")
    public class JsonController {
    
        @RequestMapping("/list")
        public void list(@RequestBody User user) {
            System.out.println(user);
        }
    }
    
    
  • 编写controller,响应数据 @ResponseBody

    package com.czxy.mvcanno.controller;
    
    import com.czxy.mvcanno.domain.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    @Controller
    @RequestMapping("/json")
    public class JsonController {
    
        @RequestMapping("/list")
        @ResponseBody
        public List<User> list(@RequestBody User user) {
            System.out.println(user);
            //响应数据
            List<User> list = new ArrayList<>();
            list.add(new User(1,"jack","1234"));
            list.add(new User(2,"rose","6666"));
            list.add(new User(3,"tom","loverose"));
    
            return list;
        }
    }
    
    
  • postman测试
    在这在这里插入图片描述里插入图片描述

3.4 常见注解

  • @JsonIgnore 作用是json序列化时将java bean中的一些属性忽略掉~
public class User {

    @JsonIgnore
    private List<String> hobby;
  • @JsonFormat 格式化日期
public class User {

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
    private Date birthday;
string json = ""; string newfilename = ""; string path = ""; try { if (context.Request.Files["file_upload"] != null && context.Request.Files["file_upload"].FileName != "") { string hzm = System.IO.Path.GetExtension(context.Request.Files["file_upload"].FileName);//后缀名 如 .doc string[] a = { ".txt", ".jpg", ".jpeg", ".gif", ".png", ".docx", ".doc", ".xlsx", ".xls", ".rar", ".zip",".pdf" };//设定好了的格式 if (!a.Contains(hzm)) { json = "{\"statusCode\":\"300\",\"message\":\"文件格式不正确\",\"navTabId\":\"nav6\",\"rel\":\"\",\"callbackType\":\"\",\"forwardUrl\":\"\"}"; return json; } else { int defaulsize = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["filesize"]);//取得设置的默认文件的大小 int filesize = (context.Request.Files["file_upload"].ContentLength) / 1024; //取得上传的文件的大小,单位为bytes if (filesize < defaulsize) { #region 对文件进行操作 newfilename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + hzm;//文件的新名字 如20120711105734222.doc path = System.Web.HttpContext.Current.Server.MapPath("~/UploadFile//");//文件保存的路径 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } #endregion } else { //超过了文件的大小 json = "{\"statusCode\":\"300\",\"message\":\"上传的文件超过了3000M,请重新选择\",\"navTabId\":\"nav6\",\"rel\":\"\",\"callbackType\":\"\",\"forwardUrl\":\"\"}"; return json; } } } } catch (Exception) { json = "{\"statusCode\":\"300\",\"message\":\"文件格式不正确\",\"navTabId\":\"nav6\",\"rel\":\"\",\"callbackType\":\"\",\"forwardUrl\":\"\"}"; return json; } if (newfilename != "") { context.Request.Files["file_upload"].SaveAs(path + newfilename); //保存文件 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值