1、前端调用微信的js接口wx.uploadimage接口上传图片会返回一个serverId
微信公众平台官网:
https://developers.weixin.qq.com/doc/offiaccount/Getting_Started/Overview.html
2、后端可根据获取临时素材接口下载该图片(get方式)
https://api.weixin.qq.com/cgi-bin/media/get?access_token=tokenValue&media_id=serverId
public static String downFileWxImg(String mediaId,String accessToken,String path) {
String fullPath = "";
try {
//获取token的地址=https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}
//下载地址
String url = MessageFormat.format("https://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}", accessToken,mediaId);
HttpGet httpGet = new HttpGet(url);
CloseableHttpClient client = HttpClients.createDefault();
HttpResponse resp = client.execute(httpGet);
if (resp.getStatusLine().getStatusCode() == 200) {
String size = resp.getFirstHeader("Content-Length").getValue();
System.out.println(MessageFormat.format("文件大小{0}", size));
String contentType = resp.getFirstHeader("Content-Type").getValue();
String fileType = ".jpg";
if (contentType.equals(MimeTypeUtils.IMAGE_JPEG_VALUE)) {
fileType = ".jpg";
} else if (contentType.equals(MimeTypeUtils.IMAGE_PNG_VALUE)) {
fileType = ".png";
} else if (contentType.equals(MimeTypeUtils.IMAGE_GIF_VALUE)) {
fileType = ".gif";
}
fullPath = path+fileType;
if (!(new File(fullPath)).exists()) {
(new File(fullPath)).createNewFile();
}
FileCopyUtils.copy(resp.getEntity().getContent(), new FileOutputStream(fullPath));
}
} catch (Exception e) {
e.printStackTrace();
}
return fullPath;
}
需要注意的问题,前端初始化jssdk的时候会用到签名appId等信息,必须和后端对应,否则会报mediaId
wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '', // 必填,公众号的唯一标识
timestamp: , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名
jsApiList: [] // 必填,需要使用的JS接口列表
});
无效