企業在使用接口時,對多媒體文件、多媒體消息的獲取和調用等操作,是通過media_id來進行的。通過本接口,企業可以上傳或下載多媒體文件。
注意,每個多媒體文件(media_id)會在上傳到微信服務器3天后自動刪除,以節省服務器資源
上傳媒體文件:
- /**
- * 上傳媒體文件
- * @param accessToken 接口訪問憑證
- * @param type 媒體文件類型,分別有圖片(image)、語音(voice)、視頻(video),普通文件(file)
- * @param media form-data中媒體文件標識,有filename、filelength、content-type等信息
- * @param mediaFileUrl 媒體文件的url
- * 上傳的媒體文件限制
- * 圖片(image):1MB,支持JPG格式
- * 語音(voice):2MB,播放長度不超過60s,支持AMR格式
- * 視頻(video):10MB,支持MP4格式
- * 普通文件(file):10MB
- * */
- public static WeixinMedia uploadMedia(String accessToken, String type, String mediaFileUrl) {
- WeixinMedia weixinMedia = null;
- // 拼裝請求地址
- String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
- uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
- // 定義數據分隔符
- String boundary = "------------7da2e536604c8";
- try {
- URL uploadUrl = new URL(uploadMediaUrl);
- HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
- uploadConn.setDoOutput(true);
- uploadConn.setDoInput(true);
- uploadConn.setRequestMethod("POST");
- // 設置請求頭Content-Type
- uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
- // 獲取媒體文件上傳的輸出流(往微信服務器寫數據)
- OutputStream outputStream = uploadConn.getOutputStream();
- URL mediaUrl = new URL(mediaFileUrl);
- HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
- meidaConn.setDoOutput(true);
- meidaConn.setRequestMethod("GET");
- // 從請求頭中獲取內容類型
- String contentType = meidaConn.getHeaderField("Content-Type");
- // 根據內容類型判斷文件擴展名
- String fileExt = WeixinUtil.getFileEndWitsh(contentType);
- // 請求體開始
- outputStream.write(("--" + boundary + "\r\n").getBytes());
- outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
- outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
- // 獲取媒體文件的輸入流(讀取文件)
- BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
- byte[] buf = new byte[8096];
- int size = 0;
- while ((size = bis.read(buf)) != -1) {
- // 將媒體文件寫到輸出流(往微信服務器寫數據)
- outputStream.write(buf, 0, size);
- }
- // 請求體結束
- outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
- outputStream.close();
- bis.close();
- meidaConn.disconnect();
- // 獲取媒體文件上傳的輸入流(從微信服務器讀數據)
- InputStream inputStream = uploadConn.getInputStream();
- InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
- BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
- StringBuffer buffer = new StringBuffer();
- String str = null;
- while ((str = bufferedReader.readLine()) != null) {
- buffer.append(str);
- }
- bufferedReader.close();
- inputStreamReader.close();
- // 釋放資源
- inputStream.close();
- inputStream = null;
- uploadConn.disconnect();
- // 使用JSON-lib解析返回結果
- JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
- // 測試打印結果
- System.out.println("打印測試結果"+jsonObject);
- weixinMedia = new WeixinMedia();
- weixinMedia.setType(jsonObject.getString("type"));
- // type等於 縮略圖(thumb) 時的返回結果和其它類型不一樣
- if ("thumb".equals(type))
- weixinMedia.setMediaId(jsonObject.getString("thumb_media_id"));
- else
- weixinMedia.setMediaId(jsonObject.getString("media_id"));
- weixinMedia.setCreatedAt(jsonObject.getInt("created_at"));
- } catch (Exception e) {
- weixinMedia = null;
- String error = String.format("上傳媒體文件失敗:%s", e);
- System.out.println(error);
- }
- return weixinMedia;
- }
下載媒體文件:
- /**
- * 獲取媒體文件
- * @param accessToken 接口訪問憑證
- * @param media_id 媒體文件id
- * @param savePath 文件在服務器上的存儲路徑
- * */
- public static String downloadMedia(String accessToken, String mediaId, String savePath) {
- String filePath = null;
- // 拼接請求地址
- String requestUrl = "https://qyapi.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);
- System.out.println(requestUrl);
- try {
- URL url = new URL(requestUrl);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setDoInput(true);
- conn.setRequestMethod("GET");
- if (!savePath.endsWith("/")) {
- savePath += "/";
- }
- // 根據內容類型獲取擴展名
- String fileExt = WeixinUtil.getFileEndWitsh(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;
- }
main 示例:
- //示例
- public static void main(String[] args) {
- /**
- * 上傳多媒體文件
- */
- String access_token = WeixinUtil.getAccessToken(ParamesAPI.corpId, ParamesAPI.secret).getToken();
- //地址
- WeixinMedia weixinMedia = uploadMedia(access_token, "image", "http://localhost:8080/weixinClient/images/weather3.jpg");
- //media_id
- System.out.println("media_id:"+weixinMedia.getMediaId());
- //類型
- System.out.println("類型:"+weixinMedia.getType());
- //時間戳
- System.out.println("時間戳:"+weixinMedia.getCreatedAt());
- //打印結果
- if(null!=weixinMedia){
- System.out.println("上傳成功!");
- }else{
- System.out.println("上傳失敗!");
- }
- System.out.println("分割線*******************************************************************************************");
- /**
- * 下載多媒體文件
- */
- String savePath = downloadMedia(access_token, weixinMedia.getMediaId(), "E:/download");
- System.out.println("下載成功之後保存在本地的地址爲:"+savePath);
- }
本地測試打印結果圖:
下載成功之後保存到本地的圖片地址圖片: