通过postman进行模拟前端调用实现
java后端接口实现(Springboot实现)
@ApiOperation(value = "上传接口")
@PostMapping(value = "uploadFile")
@ResponseBody
public RtnInfo uploadFile(@ApiParam(value = "文件流") @RequestParam("file")MultipartFile file) {
RtnInfo rtnInfo = new RtnInfo();
//返回对象
Map<String, Object> jObj = new HashMap<String, Object>();
TreeMap<String, Object> params = new TreeMap<String, Object>();
//调用接口 配置上传的接口
String ret = HttpClientUtils.doPostFilePlus("/Upload", params,file, "utf-8");
if (StringUtils.isBlank(ret)) {
rtnInfo.setSystemCode(SystemCode.ERROR_5);
rtnInfo.setMsg("请求接口返回无数据!");
return rtnInfo;
}
ReturnData returnData = JSONObject.parseObject(ret, ReturnData.class);
if (returnData.isSuccess()) {
jObj.put("upload", returnData.getData());
rtnInfo.setSystemCode(SystemCode.SUCCESS);
} else {
jObj.put("upload", null);
rtnInfo.setSystemCode(SystemCode.ERROR_5);
}
return rtnInfo;
}
HttpClientUtils工具类的实现
/**
* 三方接口调用工具
*
* @param url
* @param map key 不能为null
* @param charset
* @return
*/
public static String doPostFilePlus(String url, TreeMap map, MultipartFile file, String charset) {
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
String timestamp = String.valueOf(System.currentTimeMillis());
try {
httpClient = new SSLClient();
httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//写入文件
builder.setCharset(Charset.forName("UTF-8")).addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());
//写入额外的参数
//可以通过map 循环传多个参数
builder.addTextBody("type", "1");
//封装
final HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
logger.info("response={}",response);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, charset);
logger.info("调用接口成功:{}",result);
}else{
logger.error("调用接口返回为null");
}
}
} catch (Exception ex) {
ex.printStackTrace();
logger.error("调用接口异常:e={}",ex);
}
return result;
}
注意不需要增加Content-Type= multipart/form-data; boundary=<calculated when request is sent>
我这调试的接口加啦这个参数就调不成功!!!!!!!