class="java">import org.apache.commons.codec.binary.Base64; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; /** * 文件处理工具类 */ public class FileHelpers { private static final Logger logger = LogManager.getLogger(FileHelpers.class); /** * 解析base64格式图片,并保存到临时目录 * * @param base64Str base64格式图片 * @param file 临时文件对象 * @return File Object * @throws Exception */ public static void decodeBase64ToFile(File file,String base64Str) throws Exception { OutputStream out = null; try { int prefixIndex = base64Str.indexOf(","); byte[] buffer = Base64.decodeBase64(base64Str.substring(prefixIndex + 1)); out = new FileOutputStream(file); out.write(buffer); out.flush(); } catch (Exception e) { logger.debug("decodeBase64ToFile raise exception:" + e.getMessage()); throw new Exception(e.getMessage()); } finally { if (out!=null) { out.close(); } } } } /*********************************************/ import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.util.Map; public class WeixinMediaUtils { private final Logger logger = LogManager.getLogger(ServiceWeixinMedias.class); /** * 卡券 上传图片接口 * * @param accessToken 开放平台/或者公众平台的accessToken * @param imgStream 图片base64字符串 * @return 上传成功后,返回的图片Url */ public static Map<String, Object> uploadimg(String accessToken, String imgStream) { File tempFile = null; CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { String url = String.format("%s%s", "https://api.weixin.qq.com/cgi-bin/media/uploadimg", "ACCESS_TOKEN="+accessToken)) ); tempFile = File.createTempFile("weixin_media", ".jpg"); FileHelpers.decodeBase64ToFile(tempFile, imgStream); HttpPost httpPost = new HttpPost(url); FileBody fileBody = new FileBody(tempFile); HttpEntity httpEntity = MultipartEntityBuilder.create().addPart("buffer", fileBody).build(); httpPost.setEntity(httpEntity); httpClient = HttpClients.createDefault(); response = httpClient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { String responseEntityStr = EntityUtils.toString(response.getEntity()); System.out.println(responseEntityStr); System.out.println("Response content length: " + responseEntity.getContentLength()); return JsonHelpers.deserializeToMap(responseEntityStr).orElseThrow(() -> new Exception("uploadimg failed,response realizeToMap raise Exception")); } else { throw new Exception(String.format("call weixin interface fail,file 【%s】 upload fail", tempFile.getAbsolutePath())); } } catch (Throwable t) { t.printStackTrace(); throw new Exception(t.getMessage()); } finally { if (tempFile!=null) { tempFile.delete(); } if (httpClient!=null) { HttpClientUtils.closeQuietly(httpClient); } if (response!=null) { HttpClientUtils.closeQuietly(response); } } }
? ? Java使用HttpClient,将Base64图片上传到微信!!
? ? 诸多不完善之处,敬请指正!