SpringMVC进阶,JSON进阶、文件的上传和下载

文章介绍了JSON作为数据交换格式在JavaSpringBoot中的应用,包括普通和复杂JSON对象的创建,以及如何处理包含集合和数组的对象。同时,文章详细阐述了JSON中日期格式的特殊处理方法,并提供了文件上传和下载的步骤,包括文件流的读写操作和文件路径处理。

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

JSON是一中基于JavaScript语法开放的轻量级数据交换格式,使用js语法来描述数据对象
二、JSON对象
2.1简单对象

//普通JSON对象
@RequestMapping("/jsonNomal")
@ResponseBody//可以绕过视图解析器
public User jsonNomal() {
	User user = new User("QQ", 19);
	return user;
}

2.2 复杂JSON对象
假设有如下对象new User(“小皮鞭”, 19, new Stu(“黄天霸”, 10)),转为json对象格式如下

	{
		"name":"小皮鞭",
		"age":19,
		"stu":{
			"name":"黄天霸",
			"age":10
		}
	}

2.3集合或数组返回JSON对象

//返回集合或数组对象
@RequestMapping("/jsonList")
@ResponseBody//可以绕过视图解析器
public List<User> jsonList() {
	List<User> list = Arrays.asList(new User("qq",18),new User("微信",15));
	return list;
}

2.4既有普通对象也有数组

//map集合
@RequestMapping("/jsonMap")
@ResponseBody//可以绕过视图解析器
public Object jsonMap() {
	List<User> list = Arrays.asList(new User("qq",18),new User("微信",15));
	HashMap<String, Object> map = new HashMap<>();
	map.put("name", "乳扇");
	map.put("list", list);
	return map;
}

三、JSON中对日期格式的特殊处理
在日期对象前加上注解

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")

从前台向后台上:

@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")

配置文件:

<!-- 配置文件上传解析器(按需配置)
id属性必须为:multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  <!-- 
maxUploadSize:配置文件上传的最大大小限制
value:最大的文件大小,单位是byte
	-->
<!-- <property name="maxUploadSize" value="1,048,576"></property> -->
<!-- 
使用spring的el表达式。#{1024 * 1024}
-->
<property name="maxUploadSize">
<value>#{1024 * 1024 * 10}</value>
</property>
</bean>

四、文件上传
步骤
1、前段要求:
(1)form表单提交方式必须是post提交
(2)enctype属性必须"multipart/form-data"
(3)input的属性是file且必须要有name
2、后端步骤
(1)获取上传文件输入流
(2)将文件输入流转为缓冲流
(3)获取文件输出流
使用UUID获取随机字符串与源文件的名字拼接,作为新的文件名
使用req.getServletContext().getRealPath(“/upload”)获取当前项目所在的路径
创建file文件对象
没有就创建
有就直接下一步
获取缓冲输出流
(4)使用IOUtils工具类的copy对象
(5)关流

@RequestMapping("/upload")
@ResponseBody
public void uploadFile(MultipartFile file,HttpServletRequest req) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        //获取上传问价输入流
        InputStream is = file.getInputStream();
        //将文件输入流转换为缓冲流
        bis = new BufferedInputStream(is);
        //使用UUID获取随机字符串与源文件做拼接,作为新文件名
        String str = UUID.randomUUID().toString().replaceAll("-", "");
        String newFileName = str + file.getOriginalFilename();
        //使用req.getServletContext().getRealPath("/upload")获取当前项目所在的路径
        String realPath = req.getServletContext().getRealPath("/upload");
        //创建文件对象
        File f = new File(realPath, newFileName);
        if(!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        //获取缓冲输出流
        FileOutputStream os = new FileOutputStream(f);
        bos = new BufferedOutputStream(os);
        //使用IOUtils工具类的copy方法,拷贝文件
        IOUtils.copy(bis, bos);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        if(bos!=null) {
            try {
                bos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                if(bis!=null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}

五、文件下载
前端:使用a连接,传入name属性,值为后端需要下载文件名称
后端:1、找到用户需要下载文件,判断文件存在再下载,文件不存在暂时不处理
2、通过这个文件对象new一个字节缓冲输入流
3、告诉浏览器你现在做的是下载操作,注意如果文件名是中文,需要使用URLEncoder编码
resp.setHeader(“Content-Disposition”, “attachment; filename=”
+ URLEncoder.encode(name, “UTF-8”));
4、通过response对象获取字节输出流并转为缓冲流
5、使用IOUtils工具类的copy方法,拷贝文件
6、关流

@RequestMapping("/download")
@ResponseBody
public void download(String name, HttpServletRequest req, HttpServletResponse resp){
	String str = req.getServletContext().getRealPath("/downloadfile");
	File file = new File(str, name);
	BufferedInputStream bis = null;
	BufferedOutputStream bos = null;
	if(file.exists()) {
		try {
			FileInputStream fs = new FileInputStream(file);
			bis = new BufferedInputStream(fs);
			resp.setHeader("Content-Disposition", "attachment; filename=" 
					+ URLEncoder.encode(name, "UTF-8"));
			ServletOutputStream os = resp.getOutputStream();
			bos = new BufferedOutputStream(os);
			IOUtils.copy(bis, bos);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(bos!=null) {
				try {
					bos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally {
					if(bis!=null) {
						try {
							bis.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}
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
发出的红包

打赏作者

春花.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值