Micro-credit development of the camera, local display pictures, upload download picture examples _javascript Skills

Source: Internet
Author: User
Tags json mkdir uuid

The previous micro-letter Js-sdk authorized articles to achieve the sharing interface, then here is a summary of how in the micro-letter through JS to adjust the original camera, and upload download pictures.

1. Configure

Page introduction after JSSDK authorization, incoming WX object, first configure the required interface

Wx.config ({/
  * debug:true, * *
  appid:appid, 
  timestamp:timestamp, 
  noncestr:noncestr, 
  signature : Signature,
  jsapilist: [
     ' chooseimage ',//photo or from the cell phone album Select interface
     ' Previewimage ',//preview Picture Interface
     ' Uploadimage ',/ /Upload Image Interface
     ' downloadimage '//Download Picture interface
 ]
 };

2. Adjust the photo/photo album

Put the following method in the callback function that needs to click the event

Wx.chooseimage ({
  count:1,//number, default 9
  sizetype: [' compressed '],//Suggested compression chart
  sourcetype: [' album ', ' Camera '],// Source is album, Camera
  success:function (res) {
//var localids = res.localids;//Returns the list of local IDs for the selected photos, localid can display pictures as the SRC attribute of the IMG tag  c6/> $ ('. Driver-card img '). Prop (' src ', res.localids[0]);
  Uploadphoto.uploadtoweixinserver (Res.localids[0], ' car ')
  }}
);

At this time we can see this effect, the representative of the success of the adjustment! In the successful callback of the Chooseimage method, I assign the selected photos to the IMG src that needs to be displayed (because I only have one photo here, and if there are multiple loops assigned to it), you can directly display the photos selected in the photo/album.

3. Upload Photos

In the success callback above Chooseimage, you can see that I called the Uploadtoweixinserver method, the parameter is the ID of the local photo

Uploadtoweixinserver:function (localid,type) {
      wx.uploadimage ({
        localid:localid,
        isshowprogresstips: 1,//default is 1, display progress prompts
        Success:function (res) {
//res.serverid returns the micro-server-side ID of the picture
          Uploadphoto.uploadtoowner Server (res.serverid,type);//upload to our own servers
        }}
      ;
    

After calling the Uploadimage interface, upload the picture to the micro-server, return the image ID, this time need to use Ajax asynchronous upload to their own server, call the micro-letter provided "Get temporary material" interface. Of course, it is not necessarily the choice of photos to upload immediately, but also based on the actual business needs, there is a silent upload (no progress prompts), but also in the final submission of the form when the upload together

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 (@Reque Stparam string ServerID, @RequestParam String type) throws exception{Logger.info ("RestFul of uploadphoto parameters SE
    
    rverid:{},type:{} ", Serverid,type);
      
      Try {/** saves the picture to the local server **/String photoname = type + new Date (). GetTime () + Uuid.randomuuid (). toString ();
      If the file path does not exist, create file SaveFile = new file (Pic_path + type);
      
      if (!savefile.mkdir ()) Savefile.mkdir ();
      Wechatservice.saveimagetodisk (ServerID, Photoname, Pic_path + type + "/");
      Logger.info ("Download", "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") 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 that defines a picture name by type + timestamp + unique string. If the upload succeeds, at the same time return the picture address of your server to the front end.

getInputStream

Call the micro-letter to provide access to the temporary material interface to download the image on the micro-server, parameters for the front-end submitted to the media file ID, and eventually converted the file into an input stream object

/** * Download files based on file ID * @param accesstoken * @param mediaId * @return File Stream object/public InputStream getinputs 
    Tream (String Accesstoken, String mediaId) {InputStream is = null; String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + Accesstoken + "&media_id=" + mediaId 
    ; 
      try {URL urlget = new URL (URL); 
      HttpURLConnection http = (httpurlconnection) urlget.openconnection (); Http.setrequestmethod ("get"); 
      Must be get way request 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 (); 
    Gets the file into byte stream is = Http.getinputstream (); catch (Exception e) {logger.error ("Failed to convert InputStream from Weixin server,accesstoken:{},mediaid:{} ", Accesstoken,mediaid); 
 
  return is;
 }

Service

Writes a file to its own server by looping through the parse stream object

public void Saveimagetodisk (string mediaId, String picname, String picpath) throws Exception {string Accesstoken =
    Getbaseaccesstoken (); 
    
    InputStream InputStream = getInputStream (Accesstoken, mediaId); 
    The data in the loop fetch stream is byte[], and the 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");

 } 
      } 
    } 
  }

4. Summary

So here, a simple photo, display pictures, upload the download function has been completed, in fact, the code is the best annotation! The JSSDK opens up a lot of friendly and interesting features, and then it needs to be studied ....

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.