JSJDK - preview, select, upload images

Wechat provides interfaces for previewing, selecting, and uploading pictures. Here is a record of the usefulness of these three interfaces for me.

 

1. Preview the picture: This is relatively simple, just find a preview of the picture one by one, and go directly to the code.

var picList = [];
//loop through the images to preview
$('.photoList>li>img').each(function(index, element) {
	var picUrl = $(this).attr("src");//Get the image path
	//Add image preview event
	picList[index] = picUrl;
       $(this).click(function(){
		wx.previewImage({
			current: picUrl, // currently displayed image link
			urls: picList // List of image links to preview
		});
	})
});

 

2. Select a picture: This is also relatively simple, and the help document of WeChat is also very clear. Go directly to the code.

/**
 *This method is used to select files
 */
function selectWXFile(){
	var imgStr="",IDs="";
        //File Upload
	wx.chooseImage({
    	count: 9, // default 9
	 	sizeType:['original'], // You can specify the original image or the compressed image, both by default
	 	sourceType: ['album', 'camera'], // You can specify whether the source is an album or a camera, both by default
      	success: function (res) {
            IDs = res.localIds;//Returns the local ID list of the selected photo, localId can be used as the src attribute of the img tag to display the image
            if (IDs.length == 0) {
                $.Dialog.fail("Please use the chooseImage interface to select a picture first");
                return;
            }
            //do file upload
           syncUpload(0,IDs.length,IDs);
      	}
    });
}

 

 Note : The obtained localIds must be converted to String, that is, localIds=localIds.toString() and then localIds as the src attribute of img to display the picture.

 

3. Uploading pictures: This is a bit troublesome, the premise is that multiple pictures are uploaded. Because WeChat stipulates that you can only upload one piece at a time, and if you want to upload multiple pieces, you have to upload them one by one.

The idea that is easy to think of is: after the file is selected, add a loop to the success method of the callback function, loop a local ID, and upload one. This method can implement multiple pictures in Android system, but only one picture can be uploaded in Apple, that is, no matter how many pictures are selected, only one picture will be uploaded to the WeChat server. What I use here is a recursive method, that is, after I pass a picture and display it on the page, and then call the method of uploading the file. (so there is the upload file method at the end of the select file method above).

/**
 * This method is used to upload files
 * @param start: The subscript of the local ID start (the subscript of the currently uploaded image)
 * @param end: The total number of local IDs (that is, the total number of selected pictures)
 * @param IDs: A collection of local IDs for all images selected in the current batch
 * */
function syncUpload(start,end,IDs){
	start = parseInt(start,10);
	end = parseInt(end,10);
	//alert("start="+start+"\nend="+end);
	if(start<end){
		var localId = IDs[start].toString();
		//alert("Local ID: "+localId);
	    wx.uploadImage({
	        localId: localId,
	        isShowProgressTips: 1,//Show progress bar
	        success: function (res) {
	            var serverId = res.serverId; // returns the server-side ID of the image
	            serverId = serverId.toString ();
	            //alert("Get serverID: "+serverId);
	            
	            //Display the selected image information to the page
	            var divRanId = parseInt((new Date().getTime())/10,10);
				divRanId="add_"+divRanId;
	            var imgStr="<div id='"+divRanId+"' class='add_file_upload' sign='2'>"+
	            		"<input type='hidden' name='fileServerId' value='"+serverId+"' />" +
						"<img src='"+localId+"' width='85%' height='76%' class='imgClass' onclick='deletePhoto(this);'/>" +
						"<div class='righ'><img src='images/right.png'/></div>" +
						"<form class='box-css'>" +
						"<a class='reduce' href='javascript:void(0);' onclick='reduce(this);'><img src='images/cart_btn_reduce.png'/></a>" +
						"<input style='font-size: 9pt;width:40px;padding:0px; text-align:center; float:left; display:inline-block; height:21px; border-radius:0px;margin:2px 5px; line-height:21px; border:1px solid #828282;color:#828282' type='text' onchange='qty(this);' value='1' size='2' name='fileCount' />" +
						"<a class='adds' href='javascript:void(0);' onclick='addPhotoNum(this);'><img src='images/cart_btn_add.png'/></a>" +
						"</form></div>";
				jQuery("#photoDiv").append(imgStr);//Upload successfully, add image information
				
				//Display the number of uploaded images
				var uploadNum = jQuery("#uploadNum").text();
				if(isempty(uploadNum))uploadNum=0;
				uploadNum = parseInt(uploadNum,10);
				uploadNum = uploadNum+1;
				jQuery("#uploadNum").text(uploadNum);//Add quantity
				
	            start++;
				//Delay 1s, this 1s is used to display the picture information, to avoid the problem of uploading several times in a row and finally displaying the picture at one time
	            setTimeout(function(){
	            	syncUpload(start,end,IDs);
	            },1000);
	        }
	    });
	}
};

Attention :

1. It is best to also toString() the passed localId to avoid upload failure.

2. The code for adding the selected picture information to the page is best written in the file upload method. If it is proposed separately as a method to call here, it will appear "The file is uploaded several times in a row but the page does not display the picture until the last file upload. It is almost the same as the problem of loading all the pictures at one time", and at the same time, it can also achieve the effect of "uploading one image and showing one and can tell whether the file is uploaded successfully and the number of uploads", and the delay operation added later is also for this consideration.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327085029&siteId=291194637