How to enable cameras, display images locally, and upload and download images in WeChat development

Source: Internet
Author: User
The previous article on JS-SDK authorization to achieve the sharing interface, so here to summarize how to adjust the native camera in the inside, and upload and download images. This article describes how to enable cameras, display images locally, and upload and download images.

1. configuration

After jssdk authorization is introduced on the page, the wx object is passed in. First, the required interface is configured.


Wx. config ({/* debug: true, */appId: appid, timestamp: timestamp, nonceStr: nonceStr, signature: signature, jsApiList: ['chooseimage ', // The Image taking interface 'previewimage', // the preview image interface 'uploadimage', and // The upload image interface 'downloadimage' // The Download image interface]});


2. start the photo/album

Place the following method in the callback function for the event to be clicked.


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 the call is successful! In the success callback of the chooseImage method, I assign the selected photo to the src of the img to be displayed (because I only have one picture here, if there are multiple images, use the cyclic value assignment). In this way, you can directly display the selected photos in the photo/album.

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 image to the local server **/String photoName = type + new Date (). getTime () + UUID. randomUUID (). toString (); // if the File path does not exist, File saveFi is created. Le = new File (PIC_PATH + type); 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 successful! ServerId :{}, 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 to generate a primary key rule and define the image name by type + timestamp + unique string. If the upload is successful, the image address of the server is returned to the front-end.

GetInputStream

Call the provided interface for obtaining temporary materials to download images that are still on the server. the parameter is the ID of the media file submitted by the front end, and the file is eventually converted into an input stream object.


/*** Download the file by 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"); // The request must be http in get mode. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); http. setDoOutput (true); http. setDoInput (true); System. setProperty ("sun.net. client. defaultConnectTimeout "," 30000 "); // The connection times out for 30 seconds. setProperty ("sun.net. client. defaultReadTimeout "," 30000 "); // read timeout for 30 seconds http. connect (); // get the file and convert it 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

Parses stream objects cyclically and writes files to your server.


Public void saveImageToDisk (String mediaId, String picName, String picPath) throws Exception {String accessToken = getBaseAccessToken (); InputStream inputStream = getInputStream (accessToken, mediaId ); // cyclically retrieve the data in 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 ");}}}}

The above is the detailed content of the developed method for starting the camera, displaying images locally, and uploading and downloading images. For more information, see other related articles on php Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.