服务端接口代码如下:
/** * 上传数据+实体信息 */ @RequestMapping("/upload") public String doctorAnalysis(HttpServletRequest request, @RequestParam(value = "userinfo") String param, @RequestParam(value = "file") MultipartFile file) { logger.info("userinfo json => {}", param); logger.info("上传成功{}", file.getOriginalFilename()); File saveFile = new File("D:\\"+file.getOriginalFilename()); if (!saveFile.exists()) { saveFile.mkdirs(); } try { file.transferTo(saveFile); } catch (IOException e) { logger.error(e.getMessage(), e); e.printStackTrace(); } return "上传成功"; }
PostMan 如下
OpenFeign
@FeignClient(name = "vipsoft", url = "${api.url}") public interface ICallbackFeignService { /** * 上传文件 * * 注意: 使用openfeign传递参数含有文件类型时必须指定 consumes = MediaType.MULTIPART_FORM_DATA_VALUE * * @param param 需要将对象转成JSON,如果直接传对象出去,将会变成 Key Value的形式 * @return */ @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) String upload(@RequestPart("result") String param, @RequestPart("file") MultipartFile file); }
package com.vipsoft.web; import com.vipsoft.web.rpc.ICallbackFeignService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.FileInputStream; @SpringBootTest public class AppCallbackTest { @Autowired ICallbackFeignService appCallbackFeignService; @Test void Upload() throws Exception { File file = new File("D:\\Users\\Desktop\\fanye.mp4"); //这里的第一个参数值 file 是对应上面feign的文件注解中的@RequestPar中的name。一定要对应上 MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "application/octet-stream;charset=utf-8", new FileInputStream(file)); UserInfo param = new UserInfo(); param.setUserName("张三"); param.setAge(40); appCallbackFeignService.upload(multipartFile); } }