Home > php教程 > PHP开发 > Wechat java implements js-sdk image upload and download complete process

Wechat java implements js-sdk image upload and download complete process

高洛峰
Release: 2016-12-09 13:31:44
Original
1331 people have browsed it

A project I recently worked on happened to use the image upload interface of WeChat js-sdk. Let me summarize it here.

You can know the basic configuration of using js api here

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

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

I don’t use checkJsApi here Determine whether the current client version supports the specified JS interface, OK. By looking at the development documents, we know that when calling the js interface, the permission verification configuration must be injected directly through the config interface

<code class="hljs cs">wx.config({
  debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  appId: &#39;&#39;, // 必填,公众号的唯一标识
  timestamp: , // 必填,生成签名的时间戳
  nonceStr: &#39;&#39;, // 必填,生成签名的随机串
  signature: &#39;&#39;,// 必填,签名,见附录1
  jsApiList: [] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});</code>
Copy after login

The code to obtain the parameters in the config is as follows. I only use the chooseImage and uploadImage interfaces here. The chooseImage interface is used to take pictures or select from the mobile phone album. Picture interface, uploadImage interface is used to upload pictures, so just write these 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";
  
    // 注意 URL 一定要动态获取,不能 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 = "";
  
    //注意这里参数名必须全部小写,且必须有序
    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,></string,></string,></code>
Copy after login

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>
Copy after login

When the injection permission verification is successful, it will enter the ready interface, then we Just continue the operations we need in the ready interface

<code class="hljs javascript">wx.ready(function(){
    //拍照或从手机相册中选图接口
    wx.chooseImage({
      count: 1, // 最多能选择多少张图片,默认9
      sizeType: [&#39;original&#39;, &#39;compressed&#39;], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: [&#39;album&#39;, &#39;camera&#39;], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
        //上传图片接口
        wx.uploadImage({
          localId: localIds.toString(), // 需要上传的图片的本地ID,由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1,显示进度提示
          success: function (res) {
            var serverId = res.serverId; // 返回图片的服务器端ID
          }
        });
      }
    });
  });</code>
Copy after login

With the above code, we have uploaded the image to the WeChat server, but the image we uploaded to the WeChat server can only be saved for 3 days, so after uploading we have to Download to our local server. WeChat download multimedia interface is used here

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

access_token=ACCESS_TOKEN&media_id=MEDIA_ID

where media_id It is our serverId above, so we can download the image 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 {
 /**
  * 根据内容类型判断文件扩展名
  *
  * @param contentType 内容类型
  * @return
  */
 public static 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;
 }
 /**
  * 获取媒体文件
  * @param accessToken 接口访问凭证
  * @param mediaId 媒体文件id
  * @param savePath 文件在本地服务器上的存储路径
  * */
 public static String downloadMedia(String accessToken, String mediaId, String savePath) {
  try {
   accessToken = WeixinUtil.getAccessToken1().getToken();
  } catch (IOException e) {
   e.printStackTrace();
  }
  String filePath = null;
  // 拼接请求地址
  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 += "/";
   }
   // 根据内容类型获取扩展名
   String fileExt = DloadImgUtil .getFileexpandedName(conn.getHeaderField("Content-Type"));
   // 将mediaId作为文件名
   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("下载媒体文件成功,filePath=" + filePath);
   System.out.println(info);
  } catch (Exception e) {
   filePath = null;
   String error = String.format("下载媒体文件失败:%s", e);
   System.out.println(error);
  }
  return filePath;
 }
}
</code>
Copy after login

This completes the js-sdk image upload and download.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template