IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发测试 -> SpringBoot2——HttpMessageConverter与文件上传下载(笔记) -> 正文阅读

[开发测试]SpringBoot2——HttpMessageConverter与文件上传下载(笔记)

HttpMessageConverter

HttpMessageConverter:报文信息转换器,将请求报文转换为Java对象,或者将Java对象转换为相应报文。所拥有两个注解和两个类型:

  • @RequestBody
  • @ResponseBody
  • RequestEntity
  • ResponseEntity

@RequestBody

可以获取情感求体,需要在控制器方法设置一个形参,使用 @RequestBody 进行标识,当前请求的请求体就会为当前注解所标识的形参赋值。

<!DOCTYPE html>
<html lang="en" xmlns:th="http:/www.thymeleaf.org">
<head>
	<meta charset="UTF-8"/>
	<title>首页</title>
</head>
	<body>
	<h1>首页</h1>
	<form th:action="@{/testRequestBody}" method="post">
		用户名:<input type="text" name="user_name"/></br>
		密码:<input type="password" name="password"/></br>
		<input type="submit" value="提交"/>
	</form>
	</body>
</html>

package com.controller;

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.RequestMethod;

@Controller
public class indexController {
	@RequestMapping("/")
	public String LocateIndexPage() {
		return "index";
	}
	@RequestMapping(value = "/testRequestBody", method=RequestMethod.POST)
	public String testRequestBody(@RequestBody String requestBody) {
		System.out.println("requestBody:"+requestBody);
		return "success";
	}
}

RequestEntity

RequestEntity封装请求报文的一种类型,报文会赋值给该形参,通过getHeader获取头信息,通过getBody获取请求体信息。

package com.controller;

import org.springframework.http.RequestEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class indexController {
	@RequestMapping("/")
	public String LocateIndexPage() {
		return "index";
	}
	@RequestMapping(value = "/testRequestBody", method=RequestMethod.POST)
	public String testRequestBody(RequestEntity<String> requestEntity) {
		System.out.println(requestEntity.getHeaders());
		System.out.println(requestEntity.getBody());
		System.out.println(requestEntity.getMethod());
		return "success";
	}
}

@ResponseBody

package com.controller;

import org.springframework.http.RequestEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class indexController {
	@RequestMapping("/")
	public String LocateIndexPage() {
		return "index";
	}
	@RequestMapping(value = "/testRequestBody", method=RequestMethod.POST)
	@ResponseBody
	public String testRequestBody(RequestEntity<String> requestEntity) {
		return requestEntity.getHeaders() + "\n" +  requestEntity.getBody()+"\n" + requestEntity.getMethod();
	}
}

将对象变为json格式

创建User对象

package com.entity;

public class User {
   private Integer id;
   private String user_name;
   private String password;
   private Integer age;
   private String  sex;
   /*构造*/
   public User() {}

   
   public User(Integer id, String user_name, String password, Integer age, String sex) {
   	super();
   	this.id = id;
   	this.user_name = user_name;
   	this.password = password;
   	this.age = age;
   	this.sex = sex;
   }


   /*方法*/
   public Integer getId() {
   	return id;
   }
   public void setId(Integer id) {
   	this.id = id;
   }
   public String getUser_name() {
   	return user_name;
   }
   public void setUser_name(String user_name) {
   	this.user_name = user_name;
   }
   public String getPassword() {
   	return password;
   }
   public void setPassword(String password) {
   	this.password = password;
   }
   public Integer getAge() {
   	return age;
   }
   public void setAge(Integer age) {
   	this.age = age;
   }
   public String getSex() {
   	return sex;
   }
   public void setSex(String sex) {
   	this.sex = sex;
   }
}

主页

<!DOCTYPE html>
<html lang="en" xmlns:th="http:/www.thymeleaf.org">
<head>
	<meta charset="UTF-8"/>
	<title>首页</title>
</head>
	<body>
	<h1>首页</h1>
	<a th:href="@{/testResponseUser}">响应User对象</a>

	</body>
</html>

controller


package com.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.entity.User;

@Controller
public class indexController {
	@RequestMapping("/")
	public String LocateIndexPage() {
		return "index";
	}
	@RequestMapping(value = "/testResponseUser")
	@ResponseBody
	public User testRequestUser() {
		return new User(1001,"admin","123456",23,"男");
	}
}

此处是可以直接解析为json格式的字符串,因为SpringBoot已经引入了处理该对象的包。
在这里插入图片描述

@RestController

即,@ResponseBody+@Controller,使得该控制器下的组件都有了 @ResponseBody 注解。

ResponseEntity

该方法用于控制器方法的返回值类型。即,自定义的相应报文。常用于文件下载部分。

上传与下载

主页代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http:/www.thymeleaf.org">
<head>
	<meta charset="UTF-8"/>
	<title>首页</title>
</head>
	<body>
		<h1>首页</h1>
		<a th:href="@{/down}">下载文件1</a>
		<form th:action="@{/up}" method="post" enctype="multipart/form-data">
		 	头像:<input type="file" name="photo">
		 	<input type="submit" value="提交"/>
		</form>
	</body>
</html>

下载

我们在webapp下,放置一个1.jpg文件,作为我们要下载的文件。

  • 此处注意,如果用的不是SpringBoot自带的tomcat,请放置在resource的static中。
  • 笔者是通过Maven来进行项目的,因此用的是Spring Boot自带的Tomcat。此处的webapp是不存在的,需要自己创建。如果没有,此处的getRealPath会定位到SpringBoot Tomcat的临时路径中寻找,导致查找失败。(因为它是Servlet的原生方法,如果不设置则找不到static
  • 创建后,我们会发现类似于我们JavaWeb的文件结构
    在这里插入图片描述- 此外,建议不要通过当前的整个储存的方式传输文件,可以通过流的方式进行传输,避免溢出。可以用Servletresponse或者FileSystemResource或为ResponseEntity中放入OutputStream来执行。
package com.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FileupdownController {
	@RequestMapping("/down")
	public ResponseEntity<byte[]> downTheFile(HttpSession session) throws IOException{
		//获取ServletContext对象
		ServletContext servletContext = session.getServletContext();
		//获取服务器中的URL
		String realPath = servletContext.getRealPath("/1.jpg");
		System.out.println(realPath);
		//使用输入流
		InputStream is = new FileInputStream(realPath);


		//创建字节输入流,此处如果文件过大,容易溢出 
		//一般用流的方式遍传边读,SpringBoot允许用FileSystemResource来以流的方式输出
		byte[] bytes = new byte[is.available()];
		//读入数据
		is.read(bytes);
        //创建HttpHeaders对象设置相应头信息
        MultiValueMap<String,String> headers = new HttpHeaders();
        //下载方式,下载文件名字
        headers.add("Content-Disposition", "attachment;filename=1.jpg");
        //设置响应码
        HttpStatus statusCode = HttpStatus.OK;
        //设置ResponseEntity对象
        //此处<>更多指的是Body的类型
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes,headers,statusCode);
        //关闭输入流
        is.close();
		return responseEntity;

	}
}

上传

SpringBoot已经帮我们设置好了需要的解析器Jar包。我们直接使用即可。

我们可以在application.properties处,控制上传的大小

#设置单个文件上传大小,默认大小:1MB,
spring.servlet.multipart.max-file-size=1MB
#设置总上传文件的大小,默认大小:10MB,
spring.servlet.multipart.max-request-size=10MB
package com.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class FileupdownController {
	@RequestMapping("/up")
	public String upTheFile(MultipartFile photo,HttpSession session)throws Exception {
		String fileName = photo.getOriginalFilename();
		ServletContext servletContext = session.getServletContext();
		String photoPath = servletContext.getRealPath("/photo");
		File file = new File(photoPath);
		if(!file.exists()) {
			file.mkdir();
		}
		/*
		 * 解决重名文件问题
		 * */
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		//生成随机UUID,然后将‘-’替换掉
		String uuid = UUID.randomUUID().toString().replaceAll("-","");
		fileName = uuid+suffixName;
		//File.separator就是分隔符,不知道用什么分割,可以用它		
		photoPath = photoPath + File.separator + fileName;
		photo.transferTo(new File(photoPath));
		return "success";
	}
}
  • 多文件使用**MultipartFile[]**数组来接收。
  • 可以同时上传文件和其他文本等信息。接收方式同之前一样,不需要一个个比对。

其他部分,可参考Spring Boot的文件上传与下载

参考资源

  开发测试 最新文章
pytest系列——allure之生成测试报告(Wind
某大厂软件测试岗一面笔试题+二面问答题面试
iperf 学习笔记
关于Python中使用selenium八大定位方法
【软件测试】为什么提升不了?8年测试总结再
软件测试复习
PHP笔记-Smarty模板引擎的使用
C++Test使用入门
【Java】单元测试
Net core 3.x 获取客户端地址
上一篇文章      下一篇文章      查看所有文章
加:2022-04-18 18:12:40  更:2022-04-18 18:13:26 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 11:43:43-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码