最近在做微信公众号相关功能,需要把网络图片上传到微信素材库。由于微信开放接口不识别网络图片地址,需要把图片先下载到服务器再上传,废话不多说,直接上代码:
@Override
public JSONObject uploadImg2WXTemp(String imgPath, String appId) throws Exception {
//调用微信接口获取accessToken
String accessToken = getAccessToken(appId);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
URL url = new URL(imgPath);
//打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为5秒
conn.setConnectTimeout(5 * 1000);
InputStream inStream = null;
FileOutputStream outStream = null;
try {
//通过输入流获取图片数据
inStream = conn.getInputStream();
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
byte[] data = readInputStream(inStream);
//这个判断可以删掉,是为了兼容业务图片
if (imgPath.contains("?")){
imgPath = imgPath.split("\\?")[0];
}
String fileExtend = imgPath.substring(imgPath.lastIndexOf(".") + 1);
LocalDate now = LocalDate.now();
//文件命名随意
String filePath = "material_" + now.getYear() + "_" + now.getMonthValue() + "_" + now.getDayOfMonth()+"_"+System.currentTimeMillis()+ "." + fileExtend;
File imageFile = new File(filePath);
//创建输出流
outStream = new FileOutputStream(imageFile);
//写入数据
outStream.write(data);
MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
multiValueMap.add("media", new FileSystemResource(imageFile));
multiValueMap.add("filename", filePath);
multiValueMap.add("filelength", data.length);
String mediaType = "";
//可以查看微信公众平台文档,可以上传哪些类型图片和图片大小限制
switch (fileExtend) {
case "jpg":
mediaType = MediaType.IMAGE_JPEG_VALUE;
break;
case "png":
mediaType = MediaType.IMAGE_PNG_VALUE;
break;
case "jpeg":
mediaType = MediaType.IMAGE_JPEG_VALUE;
break;
default:
throw new Exception("请检查图片格式");
}
multiValueMap.add("content-type", mediaType);
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multiValueMap, headers);
//uploadTempUrl根据自己需求定义
ResponseEntity<String> responseEntity = restTemplate.postForEntity(
uploadTempUrl + "?access_token={access_token}&type=image", httpEntity, String.class, accessToken);
LogUtil.logApplicationInfo("上传微信临时素材:"+JSON.toJSONString(responseEntity));
boolean delete = imageFile.delete();
if (!delete) {
LogUtil.logApplicationInfo("删除下载图片报错");
}
if (HttpStatus.OK.value() != responseEntity.getStatusCodeValue()) {
LogUtil.logApplicationError(
String.format("调用微信新增素材接口失败,result:{%s}", JSON.toJSONString(responseEntity)));
return null;
}
//删除图片
return JSON.parseObject(responseEntity.getBody());
} finally {
if (Objects.nonNull(inStream)) {
inStream.close();
}
if (Objects.nonNull(outStream)) {
outStream.close();
}
}
}
private static byte[] readInputStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024 * 4];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len;
//使用一个输入流从buffer里把数据读取出来
while ((len = inStream.read(buffer)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
//关闭输入流
inStream.close();
//把outStream里的数据写入内存
return outStream.toByteArray();
}