Java springboot/springCloud项目,后端接口是用@RequestPart 注解MultipartFile类型和实体类型的参数,目的是同时提交文件和表单参数。
前端调用方式:需要使用表单(form-data)方式进行提交,content-type设置为:multipart/form-data
postman测试调用:使用form-data方式,重点是:MultipartFile类型和实体类型的参数,都需要用File方式进行提交,只不过一个真正的file,另一个是存放实体参数数据结构内容的.json文件。
后台微服务之间,通过feign调用的话,需要使用@RequestPart并匹配上相应的参数类型;同时@PostMapping中, consumes 设置为 MediaType.MULTIPART_FORM_DATA_VALUE的值;还需要在@FeignClient的configuration中配置MultipartSupportConfig;但是feign调用的话,有文件大小的限制,比如如果超过5M的话,可能会报Java Heap OutOfMemory 错误。
@FeignClient(configuration = *Feign.MultipartSupportConfig.class)
@Configuration
class MultipartSupportConfig {
@Bean
public AbstractFormWriter jsonFormWriter() {
return new JsonFormWriter();
}
}
后台微服务之间调用,如果要突破文件大小限制,可以使用apache的HttpClient接口,通过MultipartEntityBuilder 对象的addPart()方法,但是addPart中的FileBody对象的Content-type参数需要设置为application/json格式的,同postman调用一样,需要将实体类型参数的json数据内容,存入*.json文件中,才可以。
参考代码:
public static String uploadFile(String url, File file1, String fileKey, File file2, String jsonFileKey, Map<String, String> headerParams) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = "";
try {
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.setContentType(ContentType.MULTIPART_FORM_DATA.withCharset("utf-8"));
//加上此行代码解决返回中文乱码问题
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart(fileKey, new FileBody(file1, ContentType.APPLICATION_JSON.withCharset("utf-8")));
builder.addPart(jsonFileKey, new FileBody(file2, ContentType.APPLICATION_JSON.withCharset("utf-8")));
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);// 执行提交
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
// 将响应内容转换为字符串
result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
参考文章:https://www.codenong.com/50395010/