1、文件存储服务(FileService)
文件上传接口,请注意接收参数“file”
@RestController
@RequestMapping(value = "/file")
public class FileController {
@Autowired
private IFileManager fileManager;
@RequestMapping(value = "/upload",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Object upload(MultipartFile file) {
return fileManager.upload(file);
}
}
2、业务处理服务(ManageService)
业务处理的数据接收接口,请注意文件接收参数“file”
@PostMapping(value = "/insert")
public Object insert(String phone, MultipartFile file) {
return service.saveInfo(phone,file);
}
3、FeignClient上传文件
Feign上传文件接口,请注意文件上传参数“file”
import org.springframework.http.MediaType;
@FeignClient("file")
public interface IFileService {
@PostMapping(value = "/file/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
Object uploadFile(@RequestPart(value = "file") MultipartFile file);
}
4、总结
-
参数是文件类型的要用@RequestPart注解;
-
设置ContentType为multipart/form-data,即consumes = MediaType.MULTIPART_FORM_DATA_VALUE;
-
ManageService接口处的文件参数名必须与FileService的接口的文件参数名一致!
关于第3点,有话要说:如参数名不一致,则FileService接收到的文件为NULL。个人猜想,文件上传是通过输入流进行传输,参数名也被转为输入流,所以参数名不一致,则FileService则无法接收文件。如解释错误,请各位大佬留言告知,感谢!