Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Wechat jsapi in the development of Wechat how to select, upload, preview and download pictures

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to achieve Wechat jsapi in the development of Wechat how to select pictures, upload pictures, preview and download pictures, the editor thinks it is very practical, so share it for everyone to do a reference, I hope you can get something after reading this article.

Parameters.

Describe the unique identification of the appId official account. Apply the timestamp of the idtimestamp generated signature nonceStr to generate the random string signature signature of the signature

The four parameters in the above table are the credentials for initializing the call to Wechat jsapi. We have repeatedly explained how to use them in the previous sections, so we will not post how to generate the above four parameters here.

The complete jsp code is as follows:

Wechat jsapi Test-V knowledge Base Welcome to Wechat jsapi Test Interface-V knowledge Base

The basic interface determines whether the current client supports the specified js interface.

Image interface to take a picture or select a picture interface from a mobile photo album

ChooseImage

Preview picture interface

PreviewImage

Upload image API

UploadImage

Download picture interface

DownloadImage

Show picture

Wx.config ({debug: true, / / enables debug mode. The returned values of all api called will be displayed in the alert on the client side. To view the parameters passed, you can open them on the PC side, and the parameter information will be typed out through log and printed only on the PC side. AppId:'${appId}', / / required, unique ID of official account timestamp:'${timestamp}', / / required, timestamp of generating signature nonceStr:'${nonceStr}', / / required, generating random string of signature signature:'${signature}', / / required, signature See Appendix 1 jsApiList: ['checkJsApi',' chooseImage', 'previewImage',' uploadImage', 'downloadImage'] / / required, list of JS interfaces to be used, list of all JS interfaces see Appendix 2}) Wx.ready (function () {/ / 5 Photo Interface / / 5.1Photography, local image selection var images = {localId: [], serverId: []}; document.querySelector ('# chooseImage'). Onclick = function () {wx.chooseImage ({success: function (res) {images.localId = res.localIds; alert ('selected' + res.localIds.length + 'picture') $("# faceImg") .attr ("src", res.localIds [0]); / / Show the picture to the page}});} / / 5.2 Picture Preview document.querySelector ('# previewImage'). Onclick = function () {wx.previewImage ({current: 'http://www.vxzsk.com/upload//bf04c9b5-5699-421d-900e-3b68bbe58a8920160816.jpg', urls: [' http://www.vxzsk.com/upload//bf04c9b5-5699-421d-900e-3b68bbe58a8920160816.jpg', 'http://www.vxzsk.com/upload//bf04c9b5-5699-421d-900e-3b68bbe58a8920160816.jpg',' http://www.vxzsk.com/upload//bf04c9b5-5699-421d-900e-3b68bbe58a8920160816.jpg']}) }; / / 5.3 upload document.querySelector ('# uploadImage'). Onclick = function () {if (images.localId.length = = 0) {alert ('Please use the chooseImage API to select a picture first'); return;} var I = 0, length = images.localId.length; images.serverId = [] Function upload () {wx.uploadImage ({localId: images.localId [I], success: function (res) {iuploaded; / / alert ('uploaded:' + i+'/'+ length); images.serverId.push (res.serverId); if (I)

< length) { upload(); } }, fail: function (res) { alert(JSON.stringify(res)); } }); } upload(); }; // 5.4 下载图片 document.querySelector('#downloadImage').onclick = function () { if (images.serverId.length === 0) { alert('请先使用 uploadImage 上传图片'); return; } var i = 0, length = images.serverId.length; images.localId = []; function download() { wx.downloadImage({ serverId: images.serverId[i], success: function (res) { i++; alert('已下载:' + i + '/' + length); images.localId.push(res.localId); if (i < length) { download(); } } }); } download(); };}); //初始化jsapi接口 状态wx.error(function (res) { alert("调用微信jsapi返回的状态:"+res.errMsg);}); 1,上述代码html按钮代码功能已经描述的很清楚了,每点击一个按钮触发一个js功能函数。 2、点击上传图片按钮之前首先要点击选择图片按钮功能,上传图片成功后会返回serverid,所以本人认为这里非常梗,调用微信jsapi上传接口,我的图片到底上传到哪里去了呢?实际上我们把图片上传到微信服务器上了也就是临时素材里面去了,可登陆微信官方管理平台查看,你也可以调用微信临时素材接口获取图片。 3、通过以上代码,我们就已经把图片上传到微信服务器了,但是我们上传到微信服务器的图片只能保存3天,所以上传完之后我们要把图片下载到我们的本地服务器,这里用到微信下载多媒体接口http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID 其中media_id就是我们上面的serverId ,所以我们就可以把图片下载到本地了,代码如下 package com.test.weixin;import net.sf.json.JSONObject;import org.apache.log4j.Level;import org.apache.log4j.LogManager;import org.apache.log4j.Logger;import org.apache.log4j.Priority;import org.springframework.util.StringUtils;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;/**** * * @author V型知识库 www.vxzsk.com * */public class DloadImgUtil { /** * 根据内容类型判断文件扩展名 * * @param contentType 内容类型 * @return */ public static String getFileexpandedName(String contentType) { String fileEndWitsh = ""; if ("image/jpeg".equals(contentType)) fileEndWitsh = ".jpg"; else if ("audio/mpeg".equals(contentType)) fileEndWitsh = ".mp3"; else if ("audio/amr".equals(contentType)) fileEndWitsh = ".amr"; else if ("video/mp4".equals(contentType)) fileEndWitsh = ".mp4"; else if ("video/mpeg4".equals(contentType)) fileEndWitsh = ".mp4"; return fileEndWitsh; } /** * 获取媒体文件 * @param accessToken 接口访问凭证 * @param mediaId 媒体文件id * @param savePath 文件在本地服务器上的存储路径 * */ public static String downloadMedia(String accessToken, String mediaId, String savePath) { try { accessToken = DloadImgUtil.getAccessToken(); } catch (IOException e) { e.printStackTrace(); } String filePath = null; // 拼接请求地址 String requestUrl = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID"; requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId); try { URL url = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setRequestMethod("GET"); if (!savePath.endsWith("/")) { savePath += "/"; } // 根据内容类型获取扩展名 String fileExt = DloadImgUtil .getFileexpandedName(conn.getHeaderField("Content-Type")); // 将mediaId作为文件名 filePath = savePath + mediaId + fileExt; BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); FileOutputStream fos = new FileOutputStream(new File(filePath)); byte[] buf = new byte[8096]; int size = 0; while ((size = bis.read(buf)) != -1) fos.write(buf, 0, size); fos.close(); bis.close(); conn.disconnect(); String info = String.format("下载媒体文件成功,filePath=" + filePath); System.out.println(info); } catch (Exception e) { filePath = null; String error = String.format("下载媒体文件失败:%s", e); System.out.println(error); } return filePath; } /*** * 获取acess_token * 来源www.vxzsk.com * @return */ public static String getAccessToken(){ String appid="你公众号基本设置里的应用id";//应用ID String appSecret="你公众号基本设置里的应用密钥";//(应用密钥) String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appSecret+""; String backData=DloadImgUtil.sendGet(url, "utf-8", 10000); String accessToken = (String) JSONObject.fromObject(backData).get("access_token"); return accessToken; } /*** * 模拟get请求 * @param url * @param charset * @param timeout * @return */ public static String sendGet(String url, String charset, int timeout) { String result = ""; try { URL u = new URL(url); try { URLConnection conn = u.openConnection(); conn.connect(); conn.setConnectTimeout(timeout); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset)); String line=""; while ((line = in.readLine()) != null) { result = result + line; } in.close(); } catch (IOException e) { return result; } } catch (MalformedURLException e) { return result; } return result; }} 效果图如下: 选择图片弹出的图片详情 上传成功后返回的serverId

On "how to achieve Wechat development Wechat jsapi how to select pictures, upload pictures, preview and download pictures" this article shares here, I hope the above content can be of some help to you, so that you can learn more knowledge, if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report