微信企業號上傳下載多媒體文件接口詳解演示-java

企業在使用接口時,對多媒體文件、多媒體消息的獲取和調用等操作,是通過media_id來進行的。通過本接口,企業可以上傳或下載多媒體文件。

 

注意,每個多媒體文件(media_id)會在上傳到微信服務器3天后自動刪除,以節省服務器資源

 

上傳媒體文件:

 

[java] view plaincopy
 
  1. /** 
  2.  * 上傳媒體文件 
  3.  * @param accessToken 接口訪問憑證 
  4.  * @param type 媒體文件類型,分別有圖片(image)、語音(voice)、視頻(video),普通文件(file) 
  5.  * @param media form-data中媒體文件標識,有filename、filelength、content-type等信息 
  6.  * @param mediaFileUrl 媒體文件的url 
  7.  * 上傳的媒體文件限制 
  8.     * 圖片(image):1MB,支持JPG格式 
  9.     * 語音(voice):2MB,播放長度不超過60s,支持AMR格式 
  10.     * 視頻(video):10MB,支持MP4格式 
  11.     * 普通文件(file):10MB 
  12.  * */  
  13. public static WeixinMedia uploadMedia(String accessToken, String type, String mediaFileUrl) {  
  14.     WeixinMedia weixinMedia = null;  
  15.     // 拼裝請求地址  
  16.     String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";  
  17.     uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);  
  18.   
  19.     // 定義數據分隔符  
  20.     String boundary = "------------7da2e536604c8";  
  21.     try {  
  22.         URL uploadUrl = new URL(uploadMediaUrl);  
  23.         HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();  
  24.         uploadConn.setDoOutput(true);  
  25.         uploadConn.setDoInput(true);  
  26.         uploadConn.setRequestMethod("POST");  
  27.         // 設置請求頭Content-Type  
  28.         uploadConn.setRequestProperty("Content-Type""multipart/form-data;boundary=" + boundary);  
  29.         // 獲取媒體文件上傳的輸出流(往微信服務器寫數據)  
  30.         OutputStream outputStream = uploadConn.getOutputStream();  
  31.   
  32.         URL mediaUrl = new URL(mediaFileUrl);  
  33.         HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();  
  34.         meidaConn.setDoOutput(true);  
  35.         meidaConn.setRequestMethod("GET");  
  36.   
  37.         // 從請求頭中獲取內容類型  
  38.         String contentType = meidaConn.getHeaderField("Content-Type");  
  39.         // 根據內容類型判斷文件擴展名  
  40.         String fileExt = WeixinUtil.getFileEndWitsh(contentType);  
  41.         // 請求體開始  
  42.         outputStream.write(("--" + boundary + "\r\n").getBytes());  
  43.         outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());  
  44.         outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());  
  45.   
  46.         // 獲取媒體文件的輸入流(讀取文件)  
  47.         BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());  
  48.         byte[] buf = new byte[8096];  
  49.         int size = 0;  
  50.         while ((size = bis.read(buf)) != -1) {  
  51.             // 將媒體文件寫到輸出流(往微信服務器寫數據)  
  52.             outputStream.write(buf, 0, size);  
  53.         }  
  54.         // 請求體結束  
  55.         outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());  
  56.         outputStream.close();  
  57.         bis.close();  
  58.         meidaConn.disconnect();  
  59.   
  60.         // 獲取媒體文件上傳的輸入流(從微信服務器讀數據)  
  61.         InputStream inputStream = uploadConn.getInputStream();  
  62.         InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
  63.         BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  64.         StringBuffer buffer = new StringBuffer();  
  65.         String str = null;  
  66.         while ((str = bufferedReader.readLine()) != null) {  
  67.             buffer.append(str);  
  68.         }  
  69.         bufferedReader.close();  
  70.         inputStreamReader.close();  
  71.         // 釋放資源  
  72.         inputStream.close();  
  73.         inputStream = null;  
  74.         uploadConn.disconnect();  
  75.   
  76.         // 使用JSON-lib解析返回結果  
  77.         JSONObject jsonObject = JSONObject.fromObject(buffer.toString());  
  78.         // 測試打印結果  
  79.         System.out.println("打印測試結果"+jsonObject);  
  80.         weixinMedia = new WeixinMedia();  
  81.         weixinMedia.setType(jsonObject.getString("type"));  
  82.         // type等於 縮略圖(thumb) 時的返回結果和其它類型不一樣  
  83.         if ("thumb".equals(type))  
  84.             weixinMedia.setMediaId(jsonObject.getString("thumb_media_id"));  
  85.         else  
  86.             weixinMedia.setMediaId(jsonObject.getString("media_id"));  
  87.             weixinMedia.setCreatedAt(jsonObject.getInt("created_at"));  
  88.     } catch (Exception e) {  
  89.         weixinMedia = null;  
  90.         String error = String.format("上傳媒體文件失敗:%s", e);  
  91.         System.out.println(error);  
  92.     }  
  93.     return weixinMedia;  
  94. }  


下載媒體文件:

 

 

[java] view plaincopy
 
  1. /** 
  2.      * 獲取媒體文件 
  3.      * @param accessToken 接口訪問憑證 
  4.      * @param media_id 媒體文件id 
  5.      * @param savePath 文件在服務器上的存儲路徑 
  6.      * */  
  7.     public static String downloadMedia(String accessToken, String mediaId, String savePath) {  
  8.         String filePath = null;  
  9.         // 拼接請求地址  
  10.         String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";  
  11.         requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);  
  12.         System.out.println(requestUrl);  
  13.         try {  
  14.             URL url = new URL(requestUrl);  
  15.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  16.             conn.setDoInput(true);  
  17.             conn.setRequestMethod("GET");  
  18.   
  19.             if (!savePath.endsWith("/")) {  
  20.                 savePath += "/";  
  21.             }  
  22.             // 根據內容類型獲取擴展名  
  23.             String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));  
  24.             // 將mediaId作爲文件名  
  25.             filePath = savePath + mediaId + fileExt;  
  26.   
  27.             BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());  
  28.             FileOutputStream fos = new FileOutputStream(new File(filePath));  
  29.             byte[] buf = new byte[8096];  
  30.             int size = 0;  
  31.             while ((size = bis.read(buf)) != -1)  
  32.                 fos.write(buf, 0, size);  
  33.             fos.close();  
  34.             bis.close();  
  35.   
  36.             conn.disconnect();  
  37.             String info = String.format("下載媒體文件成功,filePath=" + filePath);  
  38.             System.out.println(info);  
  39.         } catch (Exception e) {  
  40.             filePath = null;  
  41.             String error = String.format("下載媒體文件失敗:%s", e);  
  42.             System.out.println(error);  
  43.         }  
  44.         return filePath;  
  45.     }  


main 示例:

 

 

[java] view plaincopy
 
  1. //示例  
  2. public static void main(String[] args) {  
  3.     /** 
  4.      * 上傳多媒體文件 
  5.      */  
  6.     String access_token = WeixinUtil.getAccessToken(ParamesAPI.corpId, ParamesAPI.secret).getToken();  
  7.     //地址  
  8.     WeixinMedia weixinMedia = uploadMedia(access_token, "image""http://localhost:8080/weixinClient/images/weather3.jpg");  
  9.     //media_id  
  10.     System.out.println("media_id:"+weixinMedia.getMediaId());  
  11.     //類型  
  12.     System.out.println("類型:"+weixinMedia.getType());  
  13.     //時間戳  
  14.     System.out.println("時間戳:"+weixinMedia.getCreatedAt());  
  15.     //打印結果  
  16.     if(null!=weixinMedia){  
  17.         System.out.println("上傳成功!");  
  18.     }else{  
  19.         System.out.println("上傳失敗!");  
  20.     }  
  21.       
  22.     System.out.println("分割線*******************************************************************************************");  
  23.     /** 
  24.      * 下載多媒體文件 
  25.      */  
  26.     String savePath = downloadMedia(access_token, weixinMedia.getMediaId(), "E:/download");  
  27.     System.out.println("下載成功之後保存在本地的地址爲:"+savePath);  
  28.   
  29. }  


本地測試打印結果圖:

 

 

下載成功之後保存到本地的圖片地址圖片:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章