本文主要是介绍HttpClient上传文件传入MultipartFile类型,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
httpClient post方式上传MultipartFile文件
注意:builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
第一个参数:"file" 表现需要调用的上传文件接口 文件名
返回 ”Required request part 'file' is not present” 错误时,就是因为该名称 和调用的 url中文件名称不一样
第二个参数:传入文件流
第三个参数:文件类型
第四个参数:上传文件的名称
/*** post请求接口* @param url* @param imageUploadFileName* @param file* @param headerParams* @param otherParams* @return*/public static String postResultMultipartFile(String url,String imageUploadFileName,MultipartFile file,Map<String,String> headerParams, Map<String,String> otherParams) {CloseableHttpClient httpClient = HttpClients.createDefault();String result = "";HttpEntity httpEntity = null;HttpEntity responseEntity = null;try {String fileName = file.getOriginalFilename();HttpPost httpPost = new HttpPost(url);//添加header
// for (Map.Entry<String, String> e : headerParams.entrySet()) {
// httpPost.addHeader(e.getKey(), e.getValue());
// }MultipartEntityBuilder builder = MultipartEntityBuilder.create();builder.setCharset(Charset.forName("utf-8"));builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
// for (Map.Entry<String, String> e : otherParams.entrySet()) {
// builder.addTextBody(e.getKey(), e.getValue());// 类似浏览器表单提交,对应input的name和value
// }httpEntity = builder.build();httpPost.setEntity(httpEntity);HttpResponse response = httpClient.execute(httpPost);// 执行提交responseEntity = response.getEntity();if (responseEntity != null) {// 将响应内容转换为字符串result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));}} catch (IOException e) {log.info("------------------{}",e.getMessage());e.printStackTrace();}catch (Exception e) {log.info("------------------{}",e.getMessage());e.printStackTrace();} finally {printLog(url, HttpMethod.POST, httpEntity, null, responseEntity);}return result;}
控制器端代码
@ApiOperation(value = "通过http调用***文件接口 上传图片到***IDC服务器")@PostMapping(value = "/upload")public BizBaseResponse<String> upload(@RequestParam("file") MultipartFile file, String dir) {String upload = null;try {upload = openApiShopFileService.upload(file,dir, true);} catch (BizException e) {log.error("通过http调用***文件接口 上传图片到***IDC服务器 异常(/openapi/shop/addShopInfoToThShop)", e);return addError(BizErrorCodeEnum.OPERATION_FAILED, e.getErrorMessage());} catch (Exception e) {log.error("通过http调用***文件接口 上传图片到***IDC服务器 异常(/openapi/shop/addShopInfoToThShop)", e);return addError(BizErrorCodeEnum.OPERATION_FAILED, "上传文件失败");}return new BizBaseResponse(upload);}
postman调用测试:
这篇关于HttpClient上传文件传入MultipartFile类型的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!