1. 程式人生 > >微信公眾號開發《四》使用微信JS-SDK實現手機圖片上傳,支援壓縮、預覽。並下載圖片到自身伺服器

微信公眾號開發《四》使用微信JS-SDK實現手機圖片上傳,支援壓縮、預覽。並下載圖片到自身伺服器

在這貼上上三篇博文連結,方便大家查閱互相學習:

本次講解微信開發第四篇:呼叫微信JS-SDK實現上傳手機圖片到伺服器,是非常常見的功能。如我們看到的使用者上傳頭像

下面是本次要實現的效果圖,支援預覽,壓縮上傳(自帶,可引數控制)


1.準備工作:工欲善其事,必先利其器,來看看開發該功能需要準備或瞭解什麼

一切就緒,我們知道要使用微信提供的JS-SDK,那就需要調通相關介面許可權。關於任何調通,這裡就不再次詳細說明,不明白者可檢視開頭介紹的文章三:

2.程式碼示例,還是老規矩,文字介紹放在程式碼中,不單獨介紹。

1)jsp部分程式碼,樣式那些就不提供了,效果如圖一
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>圖片管理</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="baidu-tc-cerfication" content="315f7ed10c0de83badbd33934a33aec1">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no,minimal-ui">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta content="telephone=no,email=no" name="format-detection">
<%@include file="includeJs.jsp" %>
<input type="hidden" id="timestamp" value="${siInfo.timestamp}">
<input type="hidden" id="nonceStr" value="${siInfo.noncestr}">
<input type="hidden" id="signature" value="${siInfo.signature}">
<input type="hidden" id="weixinOperId" value="${weixinOperId}">
</head>
<body>
<div class="weui-tab">
	<div class="weui-tab__bd">
        <div class="weui-tab__bd-item  weui-tab__bd-item--active">
			<div id="minheight" style="margin-bottom:55px;">
				<ul id="" class="" style="padding:5px;">
					<c:choose>
						<c:when test="${fn:length(listPhoto)<=0}">
							<div class="weui-uploader__bd">
								<div class="weui-uploader__input-box">
									<input id="uploaderInput" length="${fn:length(listPhoto)}" class="weui-uploader__input" type="button" accept="image/*" multiple="">
								</div>
				            </div>
						</c:when>
						<c:otherwise>
							<div class="weui-uploader__bd">
								<ul class="weui-uploader__files" id="uploaderFiles"  style="">
									<c:forEach items="${listPhoto}" var="photo">
										<li class="weui-uploader__file weui-uploader__file_status" style="background-size:contain !important;background:url(${BS}${photo.photoUrl})  no-repeat center;">
											<div class="weui-uploader__file-content">
							                    <img vid="${photo.id}" osrc="${photo.photoUrl}" src="${BS}/images/weixin/FileInfo.png">
							                </div>
										</li>
									</c:forEach>
								</ul>
								<c:if test="${fn:length(listPhoto)<5}">
									<div class="weui-uploader__input-box">
										<input id="uploaderInput" class="weui-uploader__input" type="button"   length="${fn:length(listPhoto)}" accept="image/*" multiple="">
									</div>
								</c:if>
				            </div>
						</c:otherwise>
					</c:choose>
				</ul>
            </div>
		</div>
	</div>
</div>
<script type="text/javascript" src="${BS}/js/weixin/jweixin-1.2.0.js"></script>
<script type="text/javascript" src="${BS}/js/weixin/uploadPhoto.js"></script>
</body>
</html>
2)重點程式碼uploadPhoto.js,負責呼叫介面
/**
 * @date 2017-12-01
 * @author 半山閒人
 * 提示外掛使用jqery weui,需要可以研究研究,挺不錯的一個外掛,官方網站:http://jqweui.com/
 */
var signature = $("#signature").val();//後臺傳回來的呼叫介面所需引數
var nonceStr = $("#nonceStr").val();//後臺傳回來的呼叫介面所需引數
var timestamp = $("#timestamp").val();//後臺傳回來的呼叫介面所需引數
var weixinOperId = $("#weixinOperId").val();//後臺傳回來的呼叫介面所需引數
wx.config({
    debug: false, // 開啟除錯模式,呼叫的所有api的返回值會在客戶端alert出來,若要檢視傳入的引數,可以在pc端開啟,引數資訊會通過log打出,僅在pc端時才會列印。
    appId: weixinOperId, // 必填,公眾號的唯一標識
    timestamp:timestamp, // 必填,生成簽名的時間戳
    nonceStr: nonceStr, // 必填,生成簽名的隨機串
    signature:signature,// 必填,簽名
    jsApiList: [ 
        'previewImage',
        'chooseImage',
        'downloadImage',
        'uploadImage',
        'getLocalImge',
        'getNetworkType'
     ] // 必填,需要使用的JS介面列表,所有JS介面列表見附錄2
});
wx.ready(function(){//不是wifi提示
	wx.getNetworkType({
	    success: function (res) {
	        var networkType = res.networkType; // 返回網路型別2g,3g,4g,wifi
	        if(networkType!="wifi"){
	        	$.toptip("當前你網路環境為"+networkType+",上傳請注意流量",2000,'warning');
	        }
	    }
	});
});
wx.error(function(res){
	
});
var visW = $(window).width();
var NvisW = $(window).width();
$(function(){
	$("#uploaderFiles img").on("click",function(){
		var th = $(this);
		$.confirm("是否確實刪除該圖片", function() {
			//點選確認後的回撥函式
			var src = $(th).attr("osrc");
			var id = $(th).attr("vid");
			toDelPic(id,src);
		}, function() {
			//點選取消後的回撥函式
		});
	});
	$(".weui-uploader__input").on("click",function(){
		var length = $(this).attr("length");
		length = 5-length;
		wx.chooseImage({
		    count: length, // 可選圖片張數,預設9
		    sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,預設二者都有
		    sourceType: ['album', 'camera'], // 可以指定來源是相簿還是相機,預設二者都有
		    success: function (res) {
		    	var localIds = res.localIds; // 返回選定照片的本地ID列表,localId可以作為img標籤的src屬性顯示圖片
		    	localIdArr = localIds;
		        uploadImg(localIds);
		    }
		});
	});
});

function toBackOne(){
//	var powerStationNumber = $("#powerStationNumber").val();
//	location = "/"+getProjectName()+"/wxFirst/getUserPowerStationDetail?powerStationNumber="+powerStationNumber;
}

var int = 0;
var serverIdArr = new Array();
var localIdArr = new Array();
function uploadImg(localId){//上傳成功,微信伺服器會返回一個本地ID,可以預覽
	var len = localId.length;
	wx.uploadImage({//根據本地ID獲得微信伺服器ID
	    localId: localId[int].toString(), // 需要上傳的圖片的本地ID,由chooseImage介面獲得
	    isShowProgressTips: 0, // 預設為1,顯示進度提示
	    success: function (res) {
	    	int++;
	        var serverId = res.serverId; // 返回圖片的伺服器端ID
	        serverIdArr.push(serverId);
	        if(len>int){
	        	uploadImg(localId);
	        }else{
	        	downloadImg(serverIdArr);//下載微信伺服器下的圖片
	        }
	    }
	});
}

function downloadImg(serverIdArr){//下載微信伺服器下的圖片到本地
	$.showLoading("上傳中");
	var stationId = $("#stationId").val();
	$.ajax({
		type:"POST",
		url:"/"+getProjectName()+"/wxFirst/downloadImg",
		dataType:"json",
		data:{
			serverIdArr:serverIdArr,
			localIdArr:localIdArr,
			stationId:stationId
		},
		success:function(result){
			$.hideLoading();
			if(result>0){
				$.toptip("上傳成功",2000,'success');
				setTimeout(function() {
					window.location.reload();
				},2000);
			}
		}
	});
}

window.addEventListener('DOMContentLoaded',init,false);
function toDelPic(id,src){
	//刪除圖片操作
}
到此該功能已經完成,但有個最大的不足之處,就是微信沒有提供裁剪功能,所以往往上傳圖片大小不符合需求大小。在此提供的裁剪外掛:cropper,有空的可以瞭解一下。有空也會寫一篇不使用微信上傳功能,實現圖片上傳、支援裁剪、壓縮。

如有錯誤與不足之處,歡迎大家評論區提出。