微信公众号网页开发JS_SDK之接口调用(2)
选图上传微信服务器然后下载到本地
-
首先在wx.config里的jsApiList列表写入chooseImage,uploadImage
-
html页面的weUI的Uploader上传组件
1
2
3
4
5
6
7
8
9
10
11
12
13<div class="weui-uploader" style="margin-bottom:10px">
<div class="weui-uploader__hd">
<p class="weui-uploader__title">现场照片上传 :</p>
</div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles">
</ul>
<div class="weui-uploader__input-box">
<input id="uploaderInput" class="weui-uploader__input"/>
</div>
</div>
</div> -
调用拍照或从手机相册中选图接口,上传图片接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42//上传图片的列表集合
var imageslocalId = [];
var imagesserverId = [];
//点击上传图片加号执行的方法
$("#uploaderInput").click(function() {
wx.chooseImage({
// 选择图片上限,默认9
count : 5,
// 可以指定是原图还是压缩图,默认二者都有
sizeType : [ 'original', 'compressed' ],
// 可以指定来源是相册还是相机,默认二者都有
sourceType : [ 'album', 'camera' ],
success : function(res) {
// 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
var localIdlist = res.localIds;
for(var i = 0;i<localIdlist.length;i++){
var localId = localIdlist[i];
imageslocalId.push(localIdlist[i]);
$("#uploaderFiles").append("<li class='weui-uploader__file' style='background-image: url("+localIdlist[i]+");'></li>");
wx.uploadImage({
// 需要上传的图片的本地ID,由chooseImage接口获得
localId: localId,
// 默认为1,显示进度提示
isShowProgressTips: 0,
success: function (res) {
// 返回图片的服务器端ID,即mediaId
var mediaId = res.serverId;
imagesserverId.push(mediaId);
},
fail: function (res) {
alert("上传图片失败,请稍后再试!");
}
});
}
//alert(imageslocalId);
},
fail: function (res) {
alert('选择图片失败,请稍后再试!');
}
});
}); -
上传图片放大预览和删除的html代码
1
2
3
4
5
6
7
8<div class="weui-gallery" id="gallery">
<span class="weui-gallery__img" id="galleryImg"></span>
<div class="weui-gallery__opr">
<a href="javascript:" class="weui-gallery__del">
<i class="weui-icon-delete weui-icon_gallery-delete"></i>
</a>
</div>
</div> -
上传图片放大预览和删除的js代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20//第几张图片
var imageindex;
//点击预览图片
$('#uploaderFiles').on('click','li',function(){
imageindex = $(this).index();
$("#galleryImg").attr("style",this.getAttribute("style"));
$("#gallery").fadeIn(100);
});
//再次点击隐藏放大图片
$("#gallery").on('click',function(){
$("#gallery").fadeOut(100);
});
//删除图片
$(".weui-gallery__del").click(function() {
$('#uploaderFiles').find("li").eq(imageindex).remove();
//删除图片的微信本地id和服务id
imageslocalId.splice(imageindex, 1);
imagesserverId.splice(imageindex, 1);
}); -
提交数据弹出式提示的html代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16<!-- 提交数据显示提交中 -->
<div id="loadingToast" style="display: none;">
<div class="weui-mask_transparent"></div>
<div class="weui-toast">
<i class="weui-loading weui-icon_toast"></i>
<p class="weui-toast__content">提交中...</p>
</div>
</div>
<!-- 显示提交完成 -->
<div id="toast" style="display: none;">
<div class="weui-mask_transparent"></div>
<div class="weui-toast">
<i class="weui-icon-success-no-circle weui-icon_toast"></i>
<p class="weui-toast__content">已完成</p>
</div>
</div> -
提交图片的serverid数据弹出式提示的js代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41//数据提交到后台
$("#addshuibiaodata").click(function() {
//提交数据把加载弹窗显示
var $loadingToast = $('#loadingToast');
if ($loadingToast.css('display') != 'none') return;
$loadingToast.fadeIn(100);
//微信服务器的图片的serverid列表字符串
var serverIds = imagesserverId.toString();
//ajax提交数据到后台
$.ajax({
type: "POST",
url: BASE_PATH + '/weiwork/comPort',
dataType : "json",
contentType : "application/json",
data: {"serverIds":serverIds},
success: function(data) {
if(data.resType == 0){
//加载弹窗隐藏
$loadingToast.fadeOut(100);
//提交完成弹窗显示
var $toast = $('#toast');
if ($toast.css('display') != 'none') return;
$toast.fadeIn(100);
//提交完成弹窗隐藏
setTimeout(function () {
$toast.fadeOut(100);
}, 2000);
window.location.reload();
}else{
//加载弹窗隐藏
$loadingToast.fadeOut(100);
$.messager.alert('提示',res.resMsg);
}
},
error : function(e){
//加载弹窗隐藏
$loadingToast.fadeOut(100);
alert("提交表单失败,请稍后再试!");
}
});
}); -
提交图片的地址的后台代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23@RequestMapping(value = "/comPort", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public JSONObject toaddshuibiaodata(HttpServletRequest request,String serverIds) {
JSONObject resultObject = new JSONObject();
// 为获取微信服务器图片而获取access_token
String accesstoken = jsapi_ticketUtil.getticketaccesstoken();
//把serverid的字符串转换成数组
String[] serveridlist = serverIds.split(",");
//拼接存在数据库的照片地址
String photoaddresslist = "";
//循环serveridlist数组,从微信服务器下载图片到本地
for(int i=0;i<serveridlist.length;i++) {
String photoaddress = WeiXinGetFileUtil.saveImageToDisk(accesstoken,serveridlist[i]);
if(i == serveridlist.length - 1) {
photoaddresslist = photoaddresslist+photoaddress;
}else {
photoaddresslist = photoaddresslist+photoaddress+",";
}
}
resultObject.put("msg", "success");
return resultObject;
}
获取access_token的jsapi_ticketUtil工具类,查看详情
-
从微信服务器下载临时文件工具类WeiXinGetFileUtil
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import cn.metter.common.utils.MTConstants;
public class WeiXinGetFileUtil {
//根据serverid(mediaid)和access_token获取输入字节流
public static InputStream getInputStream(String accessToken, String mediaId) {
InputStream is = null;
String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
+ accessToken + "&media_id=" + mediaId;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
//设置get或post请求方式, 此时必须是get方式请求
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
// 获取文件转化为输入byte流
is = http.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
return is;
}
//微信服务器获取图片保存到本地
public static String saveImageToDisk(String accessToken, String mediaId) {
//获取图片输入字节流
InputStream inputStream = getInputStream(accessToken, mediaId);
//设置图片的保存路径和文件名
int supplierId = MTConstants.MT_SUPPLIERID;
String file_dir = "D:/WaterServicePlatform/workOrderDispose/uploads/";
File file = new File(file_dir);
if (!file.exists() && !file.isDirectory()) {
System.out.println(file_dir + "目录不存在,需要创建");
// 创建目录
file.mkdirs();
}
String filePath = file_dir + mediaId + ".jpg";
System.out.println("路径:" + filePath);
//输出文件的输出流
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filePath);
byte[] data = new byte[10240];
int len = 0;
while ((len = inputStream.read(data)) != -1) {
fileOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回图片的全称
return mediaId + ".jpg";
}
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 WeiJia_Rao!