本文详解Java后端如何配合微信JS-SDK实现图片上传与下载。涵盖获取jsapi_ticket、生成wx.config签名参数、前端调用chooseImage和uploadImage接口,以及后端通过media_id将微信服务器临时图片下载至本地服务器的完整代码实现与注意事项。
微信JS-SDK图片上传下载概述
近期开发的项目中涉及到了微信JS-SDK的图片上传功能,现对实现过程进行总结记录。
关于JS API的基础配置说明,可参考官方文档获取相关信息。
https://mp.weixin.qq.com/wiki
t=resource/res_main&id=mp1421141115&token=&lang=zh_CN
本例未使用checkJsApi检测客户端版本是否支持指定JS接口。根据开发文档,调用任何JS接口前必须先通过config接口注入权限验证配置。
配置wx.config与获取Ticket
<code class="hljs cs">wx.config({
debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '', // 必填,公众号的唯一标识
timestamp: , // 必填,生成签名的时间戳
nonceStr: '', // 必填,生成签名的随机串
signature: '',// 必填,签名,见附录1
jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});</code>
获取config所需参数的Java代码如下,本例仅涉及chooseImage和uploadImage两个接口。其中chooseImage用于拍照或从相册选图,uploadImage用于将图片上传至微信服务器,因此jsApiList中仅需配置这两个接口。
<code class="hljs avrasm">import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
public class WxConfig {
public static void main(String[] args) {
String jsapi_ticket = "jsapi_ticket";
// 注意 URL 一定要动态获取,不能 hardcode
String url = "http://example.com";
Map<string, string=""> ret = sign(jsapi_ticket, url);
for (Map.Entry entry : ret.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
};
public static Map<string, string=""> sign(String jsapi_ticket, String url) {
Map<string, string=""> ret = new HashMap<string, string="">();
String nonce_str = create_nonce_str();
String timestamp = create_timestamp();
String string1;
String signature = "";
//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapi_ticket +
"&noncestr=" + nonce_str +
"×tamp=" + timestamp +
"&url=" + url;
System.out.println(string1);
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
ret.put("url", url);
ret.put("jsapi_ticket", jsapi_ticket);
ret.put("nonceStr", nonce_str);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
return ret;
}
private static String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
private static String create_nonce_str() {
return UUID.randomUUID().toString();
}
private static String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}
}
</string,></string,></string,></string,></code>
ticket可通过accessToken获取,具体Java代码如下:
<code class="hljs cs">public static String getTicket(String accessToken) throws ParseException, IOException {
public final static String sign_ticket_create_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
JSONObject jsonObject = new JSONObject();
JSONObject postjson=new JSONObject();
String ticket =null;
String url = sign_ticket_create_url.replace("ACCESS_TOKEN",accessToken);
System.out.print("url="+url);
String ticketurl ="";
try {
jsonObject = WeixinUtil.httpsRequest(url, "POST",postjson.toString());
ticket= jsonObject.getString("ticket");
System.out.println("ticket:"+ticket);
}catch (Exception e) {
e.printStackTrace();
}
return ticket;
};</code>
当权限验证注入成功并进入ready回调后,即可执行后续的图片操作逻辑。
前端图片选择与上传实现
<code class="hljs javascript">wx.ready(function(){
//拍照或从手机相册中选图接口
wx.chooseImage({
count: 1, // 最多能选择多少张图片,默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
//上传图片接口
wx.uploadImage({
localId: localIds.toString(), // 需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
var serverId = res.serverId; // 返回图片的服务器端ID
}
});
}
});
});</code>
通过上述代码,图片已成功上传至微信服务器。需注意,微信服务器上的图片仅保留3天,因此上传完成后需调用微信下载多媒体接口,将图片保存至本地服务器。
http://file.api.weixin.qq.com/cgi-bin/media/get?
access_token=ACCESS_TOKEN&media_id=MEDIA_ID
其中media_id对应前文获取的serverId,据此可将图片下载至本地,Java实现代码如下:
后端下载媒体文件至本地
<code class="hljs java">import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.springframework.util.StringUtils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class DloadImgUtil {
/**
* 根据内容类型判断文件扩展名
*
* @param contentType 内容类型
* @return
*/
public static String getFileexpandedName(String contentType) {
String fileEndWitsh = "";
if ("image/jpeg".equals(contentType))
fileEndWitsh = ".jpg";
else if ("audio/mpeg".equals(contentType))
fileEndWitsh = ".mp3";
else if ("audio/amr".equals(contentType))
fileEndWitsh = ".amr";
else if ("video/mp4".equals(contentType))
fileEndWitsh = ".mp4";
else if ("video/mpeg4".equals(contentType))
fileEndWitsh = ".mp4";
return fileEndWitsh;
}
/**
* 获取媒体文件
* @param accessToken 接口访问凭证
* @param mediaId 媒体文件id
* @param savePath 文件在本地服务器上的存储路径
* */
public static String downloadMedia(String accessToken, String mediaId, String savePath) {
try {
accessToken = WeixinUtil.getAccessToken1().getToken();
} catch (IOException e) {
e.printStackTrace();
}
String filePath = null;
// 拼接请求地址
String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
if (!savePath.endsWith("/")) {
savePath += "/";
}
// 根据内容类型获取扩展名
String fileExt = DloadImgUtil .getFileexpandedName(conn.getHeaderField("Content-Type"));
// 将mediaId作为文件名
filePath = savePath + mediaId + fileExt;
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(new File(filePath));
byte[] buf = new byte[8096];
int size = 0;
while ((size = bis.read(buf)) != -1)
fos.write(buf, 0, size);
fos.close();
bis.close();
conn.disconnect();
String info = String.format("下载媒体文件成功,filePath=" + filePath);
System.out.println(info);
} catch (Exception e) {
filePath = null;
String error = String.format("下载媒体文件失败:%s", e);
System.out.println(error);
}
return filePath;
}
}
</code>
至此,完成了基于JS-SDK的图片上传与下载全流程。
感谢阅读,希望本文能对各位开发者有所帮助,欢迎支持本站。