目录
如果发现本文有错误的地方,请大家毫不吝啬,多多指教,欢迎大家评论,谢谢!
一、概述
在我们实际开发项目中,有需求通过HttpCliect调用另外一个服务去上传,此时我们可以 RestTemplate 上传和下载来实现功能,是一个不错的选择。
二、RestTemplate 配置
/**
* RestTemplate配置
* 这是一种JavaConfig的容器配置,用于spring容器的bean收集与注册,并通过参数传递的方式实现依赖注入。
* "@Configuration"注解标注的配置类,都是spring容器配置类,springboot通过"@EnableAutoConfiguration"
* 注解将所有标注了"@Configuration"注解的配置类,"一股脑儿"全部注入spring容器中。
*
* @author Zou.LiPing
*
*/
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(@Qualifier("simpleClientHttpRequestFactory") ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
// 获取数据超时时间 毫秒
factory.setReadTimeout(5000);
return factory;
}
}
三、文件上传
调用者
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("file")
public class FileController {
private final RestTemplate restTemplate;
/**
* restTemplate 上传文件
* 访问地址: http://127.0.0.1:8110/file/uploadTest
* @date: 2021/5/27 21:30
* @return: java.lang.String
*/
@GetMapping("uploadTest")
public String uploadTest() {
final String url = "http://127.0.0.1:8088/oss/file/uploadFile";
MultiValueMap<String, Object> bodyParams = new LinkedMultiValueMap<>();
// String filePath = "D:\\file\\video\\图片1\\1.jpg";
String filePath = "D:\\file\\oss\\001.jpg";
// 封装请求参数
FileSystemResource resource = new FileSystemResource(new File(filePath));
bodyParams.add("file", resource);
bodyParams.add("personId","p0001");
bodyParams.add("reportNo","b0001");
bodyParams.add("category",0);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// heade 请求参数
headers.add("Authorization", UUID.randomUUID().toString());
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyParams, headers);
return restTemplate.postForObject(url, requestEntity, String.class);
}
}
生产者
/**
* 文件上传
*/
@PostMapping("/uploadFile")
@ApiOperation(value = "文件上传")
public String uploadFile(HttpServletRequest request,
@RequestParam("file") MultipartFile file,
@RequestParam("personId") String personId,
@RequestParam("reportNo") String reportNo,
@RequestParam("category") Integer category
) {
log.info("uploadFile.req personId={},reportNo={},category={}",personId,reportNo,category);
log.info("token====>{}",request.getHeader("Authorization"));
String url = fileService.uploadFile(FILE_HOST, file);
return url;
}
测试
http://127.0.0.1:8110/file/uploadTest
生产者控制输出
请求产生日志打印
: uploadFile.req personId=p0001,reportNo=b0001,category=0
: token====>109ac9c2-1448-41bb-9f6f-c99254bf7a1c
四、文件下载
调用者
/**
* 文件下载
* @param response
* @date: 2021/5/31 10:40
*/
@GetMapping("downloadTest")
public void downloadTest(HttpServletResponse response) {
String fileName = "edcb724a202d4497984cc48a240408d3.txt";
String url = "http://127.0.0.1:8088/oss/file/downloadFile?fileName="+fileName;
ResponseEntity<byte[]> rsp = restTemplate.getForEntity(url,byte[].class);
BufferedInputStream bis = null;
if (Objects.nonNull(rsp)) {
byte[] body = rsp.getBody();
if (Objects.nonNull(body)) {
try {
log.info("文件大小==>:{}", body.length);
String filename = fileName;
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
InputStream is = new ByteArrayInputStream(body);
bis = new BufferedInputStream(is);
OutputStream os = response.getOutputStream();
byte[] buffer = new byte[2048];
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
生产者
@Override
public ResponseEntity<byte[]> downloadObject(String fileName) {
fileName = "test/edcb724a202d4497984cc48a240408d3.txt";
OSSObject ossObject = ossTemplate.getObject(fileName);
HttpHeaders headers = new HttpHeaders();
ResponseEntity<byte[]> entity = null;
BufferedInputStream bis;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[10240];
try {
bis = new BufferedInputStream(ossObject.getObjectContent());
while (true) {
int len = bis.read(buf);
if (len < 0) {
break;
}
bos.write(buf, 0, len);
}
//将输出流转为字节数组,通过ResponseEntity<byte[]>返回
byte[] b = bos.toByteArray();
log.info("接收到的文件大小为:" + b.length);
HttpStatus status = HttpStatus.OK;
String imageName = "0001.txt";
headers.setContentType(MediaType.ALL.APPLICATION_OCTET_STREAM);
headers.add("Content-Disposition", "attachment;filename=" + imageName);
entity = new ResponseEntity<>(b, headers, status);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return entity;
}
测试
127.0.0.1:8110/upload/downloadTest