Spring Cloud RestTemplate 单文件上传、多文件上传

单文件上传:

服务提供者

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 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> 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 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> httpEntity = new HttpEntity<>(param, headers);
        AjaxResult reult = restTemplate.postForObject("http://服务名称/provider/fileApi/upload", httpEntity, AjaxResult.class);
        //删除临时文件
        for(int i=0;i

 

 

 

 

 

 

你可能感兴趣的:(JAVA,框架,Spring,Cloud)