圖片上傳(調用微信接口)

圖片上傳之原生方法

圖片上傳、壓縮、回顯、縮略圖放大、刪除、下載,可以參考這兒(h5方法)
https://github.com/zhangstar1331/pictureUpload
效果展示
在這裏插入圖片描述

背景

圖片上傳,我們一般用下面的H5方法,但是在安卓手機上無法一次性上傳多張圖片。爲了能滿足情況,如果是微信公衆號項目,可以調用微信上傳接口來實現。

<input class="hidden-input"  type="file" accept="image/*" style="height: 71px;opacity: 0;" multiple/>

圖片上傳之調用微信接口

1、h5頁面引入微信js

<script src="https://res.wx.qq.com/open/js/jweixin-1.2.0.js" type="text/javascript"></script>

2、調用後臺接口,進行微信初始化配置

$.ajax({
        url : "/cic-crm-web/cic/getConfig.do",
        async : true,
        type : "POST",
        headers: {"token":token},
        data : {
            "url" : encodeURIComponent(location.href.split('#')[0])
        },
        dataType : "json",
        success : function(data) {
            if (data != null) {
                conf = {'timestamp':data.timestamp, 'nonceStr':data.nonceStr, 'signature':data.signature};
                wx.config({
                    debug : false,
                    appId : "",
                    timestamp : data.timestamp, //時間戳
                    nonceStr : data.nonceStr, //隨機字符串
                    signature : data.signature, //得到的簽名
                    jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline','chooseImage','previewImage','uploadImage','downloadImage'] // 功能列表,我們要使用JS-SDK的什麼功能
                });
            }
        }
    })

3、調取攝像頭和相冊獲取圖片

	$('#idPartView .hidden-input').on('click', wxLoadImage.getImage);
	var num = 0;
	//調用微信api獲取照片
	var wxLoadImage = {
		picId:null,
		//獲取簽名信息
		init:function(){},
		//調取攝像頭和相冊獲取圖片
		getImage:function(){
			//配置一次最多上傳幾張圖片
			var count = 9;
			wxLoadImage.picId = $(this).parent();
			if (wxLoadImage.picId.parent().hasClass('onePicLimit')) {
				count = 2;
			}
			wx.ready(function () {
                //調取攝像頭和相冊
                var localIds = [];
                var leng = 0;
                wx.chooseImage({
                    count: count, // 默認9
                    sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有
                    sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有
                    success: function (res) {
                        localIds = localIds.concat(res.localIds); // 返回選定照片的本地ID列表,localId可以作爲img標籤的src屬性顯示圖片
                    	leng = localIds.length;
                    	if(window.__wxjs_is_wkwebview){//判斷ios是不是用的 wkwebview 內核 
			                for(var i = 0; i < leng; i++ ){
			                	num++;
			                    wxLoadImage._getIosImage(localIds[i],num)
			                }
			            }else{
			               	for(var i = 0; i < leng; i++ ){
			               		num++;
			               		//安卓這塊拿到的是地址,不是base64等具體圖片數據
			                	wxLoadImage._showImage(localIds[i],num)
			                }
			            }
                    }
                });
            })
		},
		//IOS處理
		_getIosImage:function(e,num){
			var iosLocalId = [];
			wx.getLocalImgData({
                localId: e, // 圖片的localID
                success: function (res) {                    
                    var localData = res.localData; // localData是圖片的base64數據,可以用img標籤顯示
                    localData = localData.replace('jgp', 'jpeg');//iOS 系統裏面得到的數據,類型爲 image/jgp,因此需要替換一下 
                    iosLocalId.push(localData);
                    for(var i = 0; i < iosLocalId.length; i++){
                        wxLoadImage._showImage(iosLocalId[i],num)
                    }      
                },fail:function(res){
                  alert("顯示失敗");
                }
            });
		},
		//展示圖片
		_showImage:function(data,num){
			var html = '<span class="addPhoto" id="addPhoto_' + num + '" style="height: 71px;"><i class="select-no deletePhoto" id="deletePhoto_' + num + '"></i><img class="smallImage" id="smallImage_'+ num + '" alt="" src="" uri="" index=' + num + ' width="100%" height="100%"/></span>';
			wxLoadImage.picId.before(html);
			var parentDiv = wxLoadImage.picId.parent();
			var smallImage = parentDiv.find('.smallImage');
			var smallImageLen = smallImage.length;
			if (wxLoadImage.picId.parent().hasClass('onePicLimit')) {
				if(smallImageLen>=2){
					parentDiv.find('.onePhoto').hide();
				}
			}else if (wxLoadImage.picId.parent().hasClass('validateInfo')) {
				if(smallImageLen>=10){
					parentDiv.find('.onePhoto').hide();
				}
			}else if(wxLoadImage.picId.parent().hasClass('noPicLimit1')){
				if(smallImageLen>=14){
					parentDiv.find('.onePhoto').hide();
				}
			}
			console.log(data)
			$('#smallImage_' + num).attr('src',data)
			console.log($('#smallImage_' + num).attr('src'))
			wxLoadImage._deletePhoto(num)
			wxLoadImage._onLoadPhoto("#addPhoto_" + num, data);
			setTimeout(function() {
				myScroll2.refresh();
			}, 300);
		},
		//上傳圖片,因爲安卓src那塊塞得是地址,不是具體的圖片數據,所以不能直接調用別的接口上傳圖片數據流。這塊可以將獲取到的微信數據上傳到服務器,然後讓後端再去服務器上下載下來,存到本地服務器
		_syncUpload:function(localIds){
            var localId = localIds.pop();
            wx.uploadImage({
                localId: localId,//需要上傳的本地ID
                isShowProgressTips:0,
                success: function (res) {
                    var serverId = res.serverId; // 返回圖片的服務器端ID
                    serverids.push(serverId);
                    //其他對serverId做處理的代碼
                    if(localIds.length > 0){
                        syncUpload(localIds);
                    }
                    if(leng==serverids.length){
                        var json = {};
                        for(var i=0;i<serverids.length;i++)
                        {
                            json[i]=serverids[i];
                        }
                        var serids=JSON.stringify(json);
                    }
                }
            });
        },
		//刪除圖片
		_deletePhoto: function(num) {
			$('#deletePhoto_' + num).on("click", function(e) {
				$('#addPhoto_' + num).parent().find('.onePhoto').show();
				$('#addPhoto_' + num).remove();
				e.stopPropagation();
			});
		},
		//點擊圖片時加載大圖
		_onLoadPhoto: function(iconPicture, imgUrl) {
			$(iconPicture).on('click', function() {
				try {
					var img = new Image();
					img.src = imgUrl;
					var width;
					var height;
					if (img.complete) {
						width = img.width;
						height = img.height;
					} else {
						img.onload = function() {
							width = img.width;
							height = img.height;
						};
					}
					var top = 0;
					var left = 0;
					var windowWidth = $(window).width();
					var windowHeight = $(window).height();
					if (width > windowWidth) {
						var proportion = windowWidth / width;
						width = windowWidth;
						height = height * proportion;
					} else if (width < windowWidth) {
						left = (windowWidth - width) / 2;
					}
					if (height < windowHeight) {
						top = (windowHeight - height) / 2;
					}
					var html = '';
					html += '<div class="jumpbox2 displayN preImg panel" id="preImg" style="top:0;background:#000;width:100%;height:100%">';
					html += '<div style="position:absolute; z-index:999;top:' + top + 'px;left:' + left + 'px;overflow:hidden;">';
					html += '<img id="preImage" style="vertical-align: middle;margin:0 auto;" alt="" src="' + imgUrl + '" width="' + width + '" height="' + height + '">';
					html += '</div></div>';

					$('body').append(html);
					$('#preImg').bind('click', function() {
						$('#preImg').hide();
						$('#preImg').unbind('click');
						$('#preImg').remove();
					});
					setTimeout(function() {
						$('#preImg').show();
					}, 200);
				} catch (e) {
					alert(e.name + '  ' + e.message);
				}
			});
		}
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章