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 realize the functions of adjusting camera, displaying pictures locally, uploading and downloading pictures in the development of Wechat

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Editor to share with you how to achieve the functions of adjusting the camera, displaying pictures locally, uploading and downloading pictures in Wechat development. I believe most people don't know much about it, so share this article for your reference. I hope you can learn a lot after reading this article, let's learn about it!

1. Configuration

After the page is authorized by jssdk, the wx object is passed in, and the required interface is configured first.

Wx.config ({/ * debug: true, * / appId: appid, timestamp: timestamp, nonceStr: nonceStr, signature: signature, jsApiList: ['chooseImage',// photo taking or image selection interface from mobile photo albums' previewImage',// preview image interface 'uploadImage',// image upload interface' downloadImage'// image download interface]}); 2. Set up photos / albums

Put the following method in the callback function that requires a click event

Wx.chooseImage ({count: 1, sizeType: ['compressed'], sourceType: [' album', 'camera'], success: function (res) {/ / var localIds = res.localIds; $(' .driver-card img') .prop ('src',res.localIds [0]); uploadPhoto.uploadToWeixinServer (res.localIds [0],' car')}})

At this time, we can see this effect, which means that the adjustment is successful! In the successful callback of the chooseImage method, I assign the selected photo to the src of the img that needs to be displayed (because I only have one photo here, if there are multiple photos assigned in a loop), so that I can directly display the selected photo in the photo / album.

3. Upload photos

In the success callback of chooseImage above, you can see that I called the uploadToWeixinServer method, and the argument is the Id of the local photo.

UploadToWeixinServer: 1

After calling the API uploadImage, upload the image to the Wechat server and return the ID of the image. In this case, you need to upload the image to your server asynchronously with ajax. Call the API "get temporary material" provided by Wechat. Of course, it is not necessary to upload the photos immediately, but also according to the actual business needs, there are silent uploads (no progress tips), or uploads together when the form is finally submitted.

Js:uploadToOwnerServer: function (serverId,type) {$.ajax ({data: {serverId:serverId,type:type}, type: "POST", url: WX_ROOT + "wechat/uploadPhoto" Success: function (json) {if (json) {var data = JSON.parse (json.data) If ('car' = = type) uploadPhoto.options.carImage = data.path + data.name else uploadPhoto.options.idCardImage = data.path + data.name}) }, Controller@RequestMapping (value = "/ uploadPhoto", method = RequestMethod.POST) public @ ResponseBody HttpResult uploadPhoto (@ RequestParam String serverId,@RequestParam String type) throws Exception {LOGGER.info ("RestFul of uploadPhoto parameters serverId: {}, type: {}", serverId,type) Try {/ * * Save the picture to the local server * * / String photoName = type + new Date (). GetTime () + UUID.randomUUID () .toString (); / / create File saveFile = new File (PIC_PATH + type) if the file path does not exist; if (! saveFile.mkdir ()) saveFile.mkdir () WechatService.saveImageToDisk (serverId, photoName, PIC_PATH + type + "/"); LOGGER.info ("Download the picture from weixin server pathL: {}", PIC_PATH + type + "/"); JSONObject data = new JSONObject (); data.put ("name", type + "/" + photoName+ ".jpg"); data.put ("path", PIC_SERVER + "/") HttpResult rs = new HttpResult (); rs.setCode (200); rs.setData (data.toJSONString ()); LOGGER.info ("Download the picture from weixin server is fulfilling server ID: {}, photoName: {}", serverId,photoName); LOGGER.info ("HttpResult data: {}", rs.getData ()); return rs } catch (Exception e) {LOGGER.error ("Download the picture from weixin server is error", serverId); return null;}

Here I use a UUID primary key generation rule to define the picture name by type + timestamp + unique string. If the upload is successful, return the image address of your server to the front end at the same time.

GetInputStream

Call the API for obtaining temporary material provided by Wechat to download the image that is still on the Wechat server. The parameter is the media file ID submitted by the front end, and finally the file is converted into an input stream object.

/ * * download the file according to the file id * @ param accessToken * @ param mediaId * @ return File Stream object * / public InputStream getInputStream (String accessToken, String mediaId) {InputStream is = null; String url = "http://www.php.cn/"+ accessToken +" & media_id= "+ mediaId; try {URL urlGet = new URL (url) HttpURLConnection http = (HttpURLConnection) urlGet.openConnection (); http.setRequestMethod ("GET"); / / must be a get request for http.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); http.setDoOutput (true); http.setDoInput (true); System.setProperty ("sun.net.client.defaultConnectTimeout", "30000") / / connection timeout 30 seconds System.setProperty ("sun.net.client.defaultReadTimeout", "30000"); / / read timeout 30 seconds http.connect (); / / convert the file to byte stream is = http.getInputStream () } catch (Exception e) {LOGGER.error ("Failed to convert inputStream from weixin server,accessToken: {}, mediaId: {}", accessToken,mediaId);} return is;} service

Write the file to your own server by cycling the stream object

Public void saveImageToDisk (String mediaId, String picName, String picPath) throws Exception {String accessToken = getBaseAccessToken (); InputStream inputStream = getInputStream (accessToken, mediaId); / / Loop to fetch data from the stream byte [] data = new byte [1024]; int len = 0; FileOutputStream fileOutputStream = null; try {fileOutputStream = new FileOutputStream (picPath+picName+ ".jpg") While (len = inputStream.read (data))! =-1) {fileOutputStream.write (data, 0, len);} LOGGER.info ("Write the fileInputStream is successful");} catch (IOException e) {LOGGER.error ("Write the fileInputStream is error") } finally {if (inputStream! = null) {try {inputStream.close ();} catch (IOException e) {LOGGER.error ("Close the fileInputStream is error") }} if (fileOutputStream! = null) {try {fileOutputStream.close ();} catch (IOException e) {LOGGER.error ("Close the fileOutputStream is error") } these are all the contents of this article entitled "how to adjust the camera, display pictures locally, upload and download pictures in Wechat development". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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