Micro-letter Js-sdk upload and download Picture interface usage Example _javascript tips

Source: Internet
Author: User
Tags readfile

This article illustrates the use of js-sdk upload and download image interface. Share to everyone for your reference, specific as follows:

The premise is already in Wx.config (), the picture interface is validated through.

The Upload Image interface (uploadimage) and download Picture interface (downloadimage) in micro-letter js-sdk are aimed at the micro-trust server itself. Subject to official documents

Note:

1. Using the Chooseimage interface to obtain a micro-client image address is the same as the weixin://xxxx

2. Upload the picture valid for 3 days, can download the picture to own server with the micro-letter multimedia interface, here obtains the ServerID namely media_id, the reference document HTTP://MP.WEIXIN.QQ.COM/WIKI/12/ 58bfcfabbd501c7cd77c19bd9cfa8354.html

3. Current multimedia file Download interface frequency limit of 10,000 times/day, if you need to increase the frequency, please mail weixin-open@qq.com, the message theme for "Request Multimedia interface calls", please give a brief description of your project, attach the product experience link, and the user volume and usage are explained.

Example 1, select a single picture and upload it to the micro-trust server

Select picture Single picture
wx.chooseimage ({
  count:1,//Default 9
  sizetype: [' original '],
  sourcetype: [' album ', ' Camera '] ,
  success:function (res) {
    var localid= res.localids[0];
    $ (' #localId '). Text (localid);
      Isshowprogresstips:1,//defaults to 1, showing progress
      success:function (res) {
        var serverid = Res.serverid;//Return to the server side of the picture Id
   $ (' #serverId '). Text (ServerID);}});


Example 2, download, just upload the picture, specify ServerID

var serverid=$ (' #serverId '). Text ();
Wx.downloadimage ({
  Serverid:serverid,//The server-side ID of the picture that needs to be downloaded, isshowprogresstips:1 by the Uploadimage interface,
  //default is 1, Show Progress Tip
  Success:function (res) {
    var localid = res.localid;//returns the local ID
    $ (' #imgTarget ') after the picture has been downloaded. attr (' src ', localid);
  }
);

Get user files from the micro-trust client, Method 2,
You can use the HTML file file field to read the client files and upload them to the server

<div class= "Container" >
  <!--Picture Type validation method 1-->
  <input type= "file" id= "file" multiple accept= "image /* "/>
  <input type=" button "id=" BTN1 "value=" Select Upload file "onclick=" Showfiles (); "/>
   
 

JS Code:

Read the picture and upload it to the server instance var filebox = document.getElementById (' file ');
  function Showfiles () {//Get array of selected files var filelist = Filebox.files;
    for (var i = 0; i < filelist.length i++) {var file = Filelist[i];
    Picture type authentication The second way if (/image\/\w+/.test (File.type)) readFile (file);
  else Console.log (File.name + ': not picture ');
  ///Read picture content for Dataurl function readFile (file) {var reader = new FileReader ();
  Reader.readasdataurl (file);
    Reader.onload = function (e) {var result = Reader.result;
  $ (' #img1 '). attr (' src ', result) upload (result);
    //upload to own server function upload (dataurl) {var data=dataurl.split (', ') [1];
    The data result is converted into binary data Data=window.atob.
    var uint=new uint8array (Data.length) for (var i = 0; i < data.length; i++) {uint[i]=data.charcodeat (i);
    var blob=new blob ([uint],{type: ' Image/jpeg '});
    Upload to server var fd=new FormData ();
    Fd.append (' file ', blob);
    Fd.append (' Isclip ', '-1 '); Fd.append (' MaxSize ', 1024*1024*10);
    Fd.append (' MinSize ', 0);
    Fd.append (' subfolder ', ' 1 ');
    Fd.append (' Automove ', true);
    Fd.append (' extention ', '. jpg ');
    Alert (' Start uploading ');
    var xhr = new XMLHttpRequest ();
    Xhr.open (' Post ', '/common/upload ', true); Listener Event Xhr.onreadystatechange = function (e) {if (xhr.readystate = = 4 && xhr.status =) {V
        AR data = eval (' (' + xhr.responsetext + ') ');
          if (data.success = = True) {alert (' Upload succeeded: ');
        alert (data.msg);
        else {alert (data.msg);
      } else {//alert (xhr.readystate);
  } xhr.send (FD);

 }
}

Read the client picture, Method 3, currently invalid, code is for reference only

Wx.chooseimage ({count:1,//Default 9 Sizetype: [' original '], SourceType: [' album ', ' Camera '], success:function (res
    ) {var localid= res.localids[0];
      Gets the Picture object try {var img=new image ();
      This setting is not valid in the micro-trust browser and will not throw an exception, and subsequent code will not execute Img.setattribute (' crossorigin ', ' Anonymous ');
        Img.onload=function () {var Canvas=document.getelementbyid (' Canvasone ');
        var ctx=canvas.getcontext (' 2d ');
        Canvas.width=img.width;
        Canvas.height=img.height;
        Ctx.clearrect (0,0,canvas.width,canvas.height);
        Ctx.drawimage (Img,0,0,img.width,img.height);
        try {upload (canvas);
          catch (E) {alert (e.name);
        alert (e.message);
    }} Img.src=localid;
      catch (E) {alert (e.name);
    alert (e.message);
}
  }
}); Upload to your own server function upload (canvas) {//due to Todataurl () browser security issue, if not the same domain picture will throw an exception//So here var Data=canvas.todataurl (' Imag
  E/jpeg ');
  Data=data.split (', ') [1]; AlerT (data.length);

 }

More readers interested in JavaScript-related content can view this site: "JavaScript in the JSON Operation tips Summary", "JavaScript switching effects and techniques summary", "JavaScript Search Algorithm Skills summary", " JavaScript animation effects and tips Summary, "JavaScript Error and debugging skills Summary", "JavaScript data structure and algorithm skills summary", "JavaScript traversal algorithm and Skills summary" and "JavaScript Mathematical operation Usage Summary"

I hope this article will help you with JavaScript programming.

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.