Recently done a project just use the micro-letter Js-sdk image upload interface, here to do a summary.
Here you can know the basic configuration using the JS API
Https://mp.weixin.qq.com/wiki
T=resource/res_main&id=mp1421141115&token=&lang=zh_cn
I do not use CHECKJSAPI to determine whether the current client version supports the specified JS interface, OK. By looking at the development document, we know that the call to the JS interface directly through the Config interface injection permission authentication configuration
<code class= "HLJS cs" >wx.config ({
debug:true,//Open debug mode, the return value of all invoked APIs will be on the client alert, to view incoming parameters, can be opened on the PC side, Parameter information is typed through log and is printed only on the PC side.
appId: ',//must fill, public number unique identification
timestamp:,//required, generate signature timestamp
noncestr: ',//must fill, generate signed random string
signature: ',//must fill, sign Name, see Appendix 1
jsapilist: []//must fill in, need to use the JS interface list, all JS interface list see Appendix 2
});</code>
Get config inside the parameters of the code below, I only use the Chooseimage and Uploadimage interface, Chooseimage interface is to take photos or from the mobile Phone album map interface, Uploadimage interface is used to upload pictures, So jsapilist just write these two.
<code class= "Hljs avrasm" >import Java.util.UUID;
Import Java.util.Map;
Import Java.util.HashMap;
Import Java.util.Formatter;
Import Java.security.MessageDigest;
Import java.security.NoSuchAlgorithmException;
Import java.io.UnsupportedEncodingException;
public class Wxconfig {public static void main (string[] args) {String jsapi_ticket = "Jsapi_ticket";
Note that the URL must be dynamically obtained, not hardcode String url = "http://example.com";
Map<string, string= "" > ret = sign (jsapi_ticket, URL);
For (Map.entry Entry:ret.entrySet ()) {System.out.println (Entry.getkey () + "," + Entry.getvalue ());
}
}; public static map<string, string= "" > Sign (String jsapi_ticket, string url) {map<string, string= "" > ret =
New hashmap<string, string= "" > ();
String nonce_str = Create_nonce_str ();
String timestamp = Create_timestamp ();
String string1;
String signature = ""; Note that the parameter name must be all lowercase and must be ordered string1 = "jsapi_ticket=" + jsapi_tIcket + "&noncestr=" + nonce_str + "xtamp=" + timestamp + "&url=" + url;
SYSTEM.OUT.PRINTLN (string1);
try {messagedigest crypt = messagedigest.getinstance ("SHA-1");
Crypt.reset ();
Crypt.update (String1.getbytes ("UTF-8"));
Signature = Bytetohex (Crypt.digest ());
catch (NoSuchAlgorithmException e) {e.printstacktrace ();
catch (Unsupportedencodingexception e) {e.printstacktrace ();
} ret.put ("url", url);
Ret.put ("Jsapi_ticket", Jsapi_ticket);
Ret.put ("Noncestr", nonce_str);
Ret.put ("timestamp", timestamp);
Ret.put ("signature", signature);
return ret;
private static String Bytetohex (final byte[] hash) {Formatter Formatter = new Formatter ();
for (byte B:hash) {Formatter.format ("%02x", b);
String result = Formatter.tostring ();
Formatter.close ();
return result; } private static String Create_nonce_str() {return Uuid.randomuuid (). toString ();
private static String Create_timestamp () {return long.tostring (System.currenttimemillis ()/1000);
}} </string,></string,></string,></string,></code>
Ticket can be obtained by Accesstoken, the code is as follows
<code class= "HLJS cs" >public static string GetTicket (String accesstoken) throws ParseException, IOException {
Public final static String Sign_ticket_create_url = "Https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token =access_token&type=jsapi ";
Jsonobject jsonobject = new Jsonobject ();
Jsonobject postjson=new jsonobject ();
String ticket =null;
String url = sign_ticket_create_url.replace ("Access_token", Accesstoken);
System.out.print ("url=" +url);
String Ticketurl = "";
try {
jsonobject = weixinutil.httpsrequest (URL, "POST", postjson.tostring ());
ticket= jsonobject.getstring ("Ticket");
System.out.println ("Ticket:" +ticket);
} catch (Exception e) {
e.printstacktrace ();
}
return ticket;
}; </code>
When the injection permission validation succeeds, it enters the ready interface, so we continue with the operation we need in the ready interface.
<code class= "Hljs javascript" >wx.ready (function () {
//photo or select interface from the phone album
wx.chooseimage ({
count:1,// The maximum number of pictures can be selected, the default 9
sizetype: [' original ', ' compressed '],//can specify whether the original image or compression diagram, the default both have
sourcetype: [' album ', ' Camera '], You can specify whether the source is a photo album or a camera, both of which have
success:function (res) {
var localids = res.localids;//Returns a list of local IDs for the selected photos. Localid can be used as an IMG tag src attribute to display picture
//Upload Image Interface
wx.uploadimage ({
localId:localIds.toString (),/////////////////////// Isshowprogresstips:1 by Chooseimage interface
,//default is 1, display progress hint
success:function (res) {
var serverid = Res.serverid; Returns the server-side ID of the picture}});};
</code>
Through the above code, we have uploaded the image to the micro-trust server, but we uploaded to the micro-trust server image can only be saved for 3 days, so after uploading we want to download the picture to our local server, where the use of micro-letter Download Multimedia interface
Http://file.api.weixin.qq.com/cgi-bin/media/get?
access_token=access_token&media_id=media_id
Where media_id is our top ServerID, so we can download the picture locally, the code is as follows
<code class= "Hljs java" >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.URL;
Import java.net.URLConnection; public class Dloadimgutil {/** * To determine the file name extension * * @param contentType Content Type * @return/public static String based on the content type *
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;
/** * Get media file * @param accesstoken Interface Access voucher * @param mediaId media file ID * @param savepath file's storage path on the local server * * * * *public static string Downloadmedia (String Accesstoken, String mediaId, String savepath) {try {Accesstoken = Weixinu
Til.getaccesstoken1 (). GetToken ();
catch (IOException e) {e.printstacktrace ();
} String filePath = null; Mosaic request Address 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 = = "/";
Gets the extension String fileext = dloadimgutil. Getfileexpandedname (Conn.getheaderfield ("Content-type") based on the content type);
MediaId as filename 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 ("Successful download media file, filepath=" + FilePath);
SYSTEM.OUT.PRINTLN (info);
catch (Exception e) {filePath = null;
String error = String.Format ("Download media file failed:%s", e);
SYSTEM.OUT.PRINTLN (Error);
return filePath;
}} </code>
This completes the js-sdk picture upload to download.
Thank you for reading, I hope to help you, thank you for your support for this site!