单文件上传:
服务提供者
controller
@RequestMapping(value = "/addProject",method = RequestMethod.POST) public AjaxResult addSave( HjProject hjProject, MultipartFile file)throws Exception { if (file != null&&!file.isEmpty()) { //上传图片到oss服务器 String url = AliyunOSSClientUtil.uploadFileImg(file, "file", hjProject.getShortName() + System.currentTimeMillis() + ".jpg"); hjProject.setProjectImage(url.substring(0,url.indexOf("?"))); } int i = hjProjectService.insertHjProject(hjProject); if(i>0){ HjCompanyProject hjCompanyProject = new HjCompanyProject(); hjCompanyProject.setCompanyId(cid); hjCompanyProject.setProjectId(hjProject.getId()); return toAjax(hjCompanyProjectService.insertHjCompanyProject(hjCompanyProject)); } return toAjax(i); }
消费者
RestTemplate
@Configuration public class RestConfiguration { @Bean @LoadBalanced public RestTemplate getRestTemplate() { return new RestTemplate(); } }
controller
@Autowired private RestTemplate restTemplate; @RequestMapping("/addProject") public AjaxResult addSave(HjProject hjProject, MultipartFile file)throws Exception { //设置请求头 HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("multipart/form-data"); headers.setContentType(type); //生成临时文件 File localFile = new File(getPath(),"/"+file.getOriginalFilename()); file.transferTo(localFile); FileSystemResource resource = new FileSystemResource(localFile); MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); param.add("file", resource);//文件 for (Field f : hjProject.getClass().getDeclaredFields()) { f.setAccessible(true); //遍历对象属性:值 param.add(f.getName(), f.get(hjProject)); } //用HttpEntity封装整个请求报文 HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(param, headers); //请求服务 AjaxResult s = restTemplate.postForObject("http://服务名称/provider/project/addProject", files, AjaxResult.class); System.out.println(s); //删除临时文件 localFile.delete(); return s; }
多文件上传:
服务消费者
controller
public AjaxResult upload(MultipartFile[] file)throws Exception{ MultiValueMap<String, Object> param = new LinkedMultiValueMap<>(); //设置请求头 HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("multipart/form-data"); headers.setContentType(type); File[] files = new File[file.length]; //遍历文件数组 for(int i=0;i<file.length;i++){ File localFile = new File(Util.getPath(),"/"+file[i].getOriginalFilename()); file[i].transferTo(localFile); files[i]=localFile; //多个MultipartFile同时添加进 MultiValueMap key为file //MultiValueMap可以让一个key对应多个value param.add("file", new FileSystemResource(localFile)); } //用HttpEntity封装整个请求报文 HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers); AjaxResult reult = restTemplate.postForObject("http://服务名称/provider/fileApi/upload", httpEntity, AjaxResult.class); //删除临时文件 for(int i=0;i<files.length;i++){ if(files[i].exists()){ System.out.println("删除临时文件"+files[i].getName()); files[i].delete(); } } return reult; }
评论 (0)