各个章节可能有关联关系,查找《SpringCloud实战教程》其他章节请参考:
http://www.yayihouse.com/yayishuwu/book/79
1. Springcloud通过OpenFeign上传文件教程
在上一章的eureka-client-feign项目基础上添加上传文件代码
(1) Feign客户端代码:
下面代码中service-one就是被调用的服务(前面一章eureka-client工程)的application.yml定义的工程名,@RequestMapping中地址/uploadFile就是被调用的服务uploadFile方法的请求地址
@FeignClient(value = "service-one")
public interface FeignClientService {
@RequestMapping(value="/uploadFile",produces= {MediaType.APPLICATION_JSON_VALUE},consumes= MediaType.MULTIPART_FORM_DATA_VALUE)
public Map uploadFile(@RequestPart("file")MultipartFile file);
}
创建一个controller类调用feign接口:
@RequestMapping("/uploadFile")
public void uploadFile(MultipartFile file, HttpServletResponse response) throws IOException {
Map result = feignClientService.uploadFile(file);
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter writer = response.getWriter();
writer.print(result);
writer.flush();
writer.close();
}
(2) 被Feign客户端调用服务的接口代码:
我在前面一节中的eureka-client项目中创建了一个controller类,里面定义一个给feign客户端调用的接口作为演示
@RequestMapping(value="/uploadFile",consumes= {MediaType.MULTIPART_FORM_DATA_VALUE})
@ResponseBody
public Map uplaodFile(MultipartFile file){
Map<String, String> map = new HashMap<>();
map.put("fileName",file.getOriginalFilename());
return map;
}
(3) 使用postman工具调用:http://127.0.0.1:9903/uploadFile