图片上传(调用微信接口)

图片上传之原生方法

图片上传、压缩、回显、缩略图放大、删除、下载,可以参考这儿(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);
				}
			});
		}
	}
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值