在为app提供服务时,经常会遇到app传过来base64格式的文件,可通过将其转换为流的方式进行提交,代码如下:
CloseableHttpClient httpclient = HttpClients.createDefault();
try{
HttpPost post = new HttpPost(url);
post.setEntity(MultipartEntityBuilder.create()
.addPart("file", new InputStreamBody(new ByteArrayInputStream(new Base64Encoder().decode(base64Str)), ""))
.addTextBody("source", SOURCE)
.addTextBody("token", token)
.addTextBody("exName", base64Str.substring(base64Str.indexOf("data:image/") + 11, base64Str.indexOf(";base64")))
.build());
HttpResponse response = httpclient.execute(post);
HttpEntity entitys = response.getEntity();
if (entitys != null) {
System.out.prinln(EntityUtils.toString(entitys));
}
}catch(Exception e){
e.printStackTrace();
}finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}