原生h5在微信端唤起选择图片后无法进行多选,因此需借用jssdk中的uploadImage进行多图选择
参考 微信公众平台接口调试工具
代码测试说明 代码在文章末尾
步骤如下
- chooseImage 选择图片
- uploadImage 上传图片至于微信服务器(临时存储3天有效)得到serverId
- 后台调用微信接口下载图片
注意
这里如果是在本地调试,上传到微信服务器返回的serverid是假的,可以使用接口调试工具中的
多媒体上传接口进行上传,后台调用微信的地址是从接口调试工具中的多媒体下载地址拿到的,相关微信前端文档仅提了一句。
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>附件创建</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<link href="../assets/css/index.css" rel="stylesheet">
<script src="../assets/js/jquery-1.8.2.min.js"></script>
<script type="text/javascript"
src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap-button.js"></script>
<script src="../assets/js/bootstrap-collapse.js"></script>
<script src="../assets/js/common.js"></script>
<style>
.name_page {
line-height: 36px;
}
.name_page .date_time {
margin: 4px 0;
margin-left: 2%;
background-image: url(../assets/img/day.png);
background-position: right;
background-repeat: no-repeat;
float: left;
border: 1px solid #cccccc;
height: 20px;
border-radius: 4px;
line-height: 20px;
}
#file {
height: 26px !important;
line-height: 26px !important;
border: 0 !important;
}
#div_file {
display: block !important;
}
</style>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse"
data-target=".nav-collapse">
<span class="icon-bar"></span> <span class="icon-bar"></span> <span
class="icon-bar"></span>
</button>
<h1>附件创建</h1>
<div class="navbar_r">
<a class="navbar_icobtn"></a>
</div>
<div class="nav-collapse collapse">
<ul class="nav" id="nav_data">
</ul>
</div>
</div>
</div>
</div>
<div class="container_con" style="margin-left: 50%">
<span> <a class="btn" onclick="chooseImage()">选择附件</a></span> <span
id="fileSize"></span>
</div>
<footer class="footer">
<div class="foot_tu">
<div id="submit" class="con_btn">保存</div>
<a href="#" class="con_close">取消</a>
</div>
</footer>
<script type="text/javascript">
var serverIds=[];
configInfo();
function configInfo() {
var apiList= ["getLocation","chooseImage","uploadImage"];
//获取wx jsdk信息
var url="url="+location.href.split('#')[0];
$.ajax({
url: "../../wechat/getWXSign",
type: "POST",
data: url,
dataType: "json",
success: function(result) {
if(result.code == "success") {
wx.config({
debug : false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId : result.map.appId, // 必填,公众号的唯一标识
timestamp : result.map.timestamp, // 必填,生成签名的时间戳
nonceStr : result.map.nonceStr, // 必填,生成签名的随机串
signature : result.map.signature,// 必填,签名
jsApiList : apiList
// 必填,需要使用的JS接口列表
});
} else {
common.comPopGo(result.msg);
$('.container_text').fadeOut();
}
},
error: function() {
common.comPopGo('系统错误!');
$('.container_text').fadeOut();
}
})
}
function chooseImage(){
// 处理成功后回调
wx.ready(function() {
wx.chooseImage({
count: 6, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
$('#fileSize').html(localIds.length+"个文件");
$.each(localIds, function(i, item) {
wx.uploadImage({
localId: item, // 需要上传的图片的本地ID,由chooseImage接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
var serverId = res.serverId; // 返回图片的服务器端ID
serverIds.push(serverId);
}
});
});
}
});
});
}
var ParentObjectID = GetQueryString("ParentObjectID");
$(function(){//加载页面
$("a.con_close").attr("href","ServiceRequest_details.html?data=4&reload=true&ObjectID="+ParentObjectID)
})
$("#submit").click(function() {//点击保存
if(!serverIds.length>0){
alert("请选择附件");
return false;
}
var json={};
json.serverIds=serverIds;
json.objectId=ParentObjectID;
var jsonData =JSON.stringify(json);
common.comPopTips();
$.ajax({
//几个参数需要注意一下
type : "POST",//方法类型
dataType : "json",//预期服务器返回的数据类型
contentType:'application/json;charset=utf-8',
url : "../../wechat/uploadFileIds",//url
data : jsonData,
success : function(result) {
debugger;
$('#loading_con').hide();
console.log(result);//打印服务端返回的数据(调试用)
if(result.success ){
//成功
alert("上传成功")
debugger;
}else{
alert("Error!"+result )
}
},
error : function() {
$('#loading_con').hide();
alert("网络异常!请稍后重试");
}
});
})
</script>
</body>
</html>
后端代码
private String getFileUrl="https://api.weixin.qq.com/cgi-bin/media/get?access_token=configToken"+"&media_id=";
/**
* https://mp.weixin.qq.com/debug/
* 上传文件 -微信choosimage ids
* @param request
* @param fileInfo
* @return
* @throws Exception
*/
@RequestMapping("/uploadFileIds")
public @ResponseBody ResultBody uploadBase(HttpServletRequest request, @RequestBody FileWechat fileInfo) throws Exception {
logger.info("===serverids is ====" + fileInfo.toString());
String realPath = "/home/upload/test/";
logger.info("===serverids is ====" + fileInfo.toString());
for (String serverid : fileInfo.getServerIds()) {
try {
String uri=getFileUrl.replaceAll("configToken", Config.WeChatToken)+serverid;
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
InputStream in = conn.getInputStream();
File dir = new File(realPath);
if (!dir.exists()) {
dir.mkdirs();
}
String ContentDisposition = conn.getHeaderField("Content-disposition");
String weixinServerFileName = ContentDisposition.substring(ContentDisposition.indexOf("filename")+10, ContentDisposition.length() -1);
realPath += weixinServerFileName;
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(realPath));
byte[] data = new byte[1024];
int len = -1;
while ((len = in.read(data)) != -1) {
bos.write(data,0,len);
}
bos.close();
in.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
logger.info("===serverid is ====" + serverid+" ;error is "+e.getMessage());
}
logger.info("===file is ====" + realPath);
}
return ResultBody.success();
}