Java-sdk: complete process for uploading and downloading images.

Source: Internet
Author: User

Java-sdk: complete process for uploading and downloading images.

The image upload interface of js-sdk is used in a recently developed project. Here we will summarize it.

The basic configurations of using js APIs can be found here.

Https://mp.weixin.qq.com/wiki

T = resource/res_main & id = mp1421141115 & token = & lang = zh_CN

I have not used checkJsApi to determine whether the current client version supports the specified JS interface. By reading the development documentation, we know that the configuration for invoking js interfaces must be directly injected with the config interface for permission verification.

<Code class = "hljs cs"> wx. config ({debug: true, // enable the debugging mode. The returned values of all called APIs are displayed in the client alert. To view the input parameters, you can open them on the pc, the parameter information is output through log and printed only on the pc end. AppId: '', // required. The unique identifier timestamp:, // required. The timestamp of the generated signature is nonceStr:''. // required, sign the random string signature: '', // required. For details, see Appendix 1 jsApiList: [] // required. List of JS interfaces to be used, for a list of all JS interfaces, see Appendix 2}). </code>

The code for obtaining parameters in config is as follows. I only use the chooseImage and uploadImage interfaces here. The chooseImage interface is the image taking interface or the image selecting interface from the mobile album. The uploadImage interface is used to upload images, so you can write only the two in jsApiList.

<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, cannot 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 all parameter names must be in lowercase, the string1 = "jsapi_ticket =" + jsapi_ticket + "& noncestr =" + nonce_str + "× tamp =" + 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,> </code>

Ticket can be obtained through 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 is verified successfully, the ready interface is displayed, so we can continue the required operations in the ready interface.

<Code class = "hljs javascript"> wx. ready (function () {// take a photo or select the image interface wx from the mobile album. chooseImage ({count: 1, // maximum number of images to select. The default value is 9 sizeType: ['original', 'computed']. // you can specify whether the source image is an image or a compressed image. Both of them have sourceType: ['alipay', 'camera '] by default. // you can specify whether the source is an album or a camera, both have success: function (res) {var localIds = res. localIds; // return the local ID list of the selected image. localId can be used as the src attribute of the img label to display the image. // the upload image interface wx. uploadImage ({localId: localIds. toString (), // The local ID of the image to be uploaded. isShowProgressTips: 1 is obtained by the chooseImage interface. // The default value is 1. The progress prompt success: function (res) is displayed) {var serverId = res. serverId; // server ID of the returned image}) ;}}) ;}); </code>

Through the above Code, we have uploaded the image to the server, but the image we uploaded to the server can only be saved for three days, after the upload, We need to download the image to our local server. Here we use the download Multimedia Interface.

Http://file.api.weixin.qq.com/cgi-bin/media/get?

Access_token = ACCESS_TOKEN & media_id = MEDIA_ID

Media_id is our serverId, so we can download the image to the local device. 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 {/*** determine the file extension ** @ param contentType content type ** @ return */public stati Based on the content type C String 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 ;} /*** obtain the media file ** @ param accessToken interface Access Credential * @ param mediaId media file id * @ param savePath file storage path on the local server **/public static String downloadMedia (String accessToken, string mediaId, String savePath) {try {accessToken = WeixinUtil. getAccessToken1 (). getToken ();} catch (IOException e) {e. printStackTrace ();} String filePath = null; // concatenate the request URL String requestUrl = "http://file.api.we Ixin.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 + = "/";} // obtain the extension String fileExt = DloadImgUtil Based on the content type. getFileexpandedName (conn. getHeaderField ("Content-Type"); // use mediaId as the file name 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 ("media file downloaded successfully, filePath =" + filePath); System. out. println (info);} catch (Exception e) {filePath = null; String error = String. format ("failed to download media file: % s", e); System. out. println (error) ;}return filePath ;}</code>

This completes the upload and download of the js-sdk image.

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

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.