ITeye博客

微信企业号上传下载多媒体文件接口详解演示-java

wusuoya · 2015-03-27 15:37 · SSH · 互联网 · Markdown

企业在使用接口时,对多媒体文件、多媒体消息的获取和调用等操作,是通过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. String boundary = "------------7da2e536604c8";
  20. try {
  21. URL uploadUrl = new URL(uploadMediaUrl);
  22. HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
  23. uploadConn.setDoOutput(true);
  24. uploadConn.setDoInput(true);
  25. uploadConn.setRequestMethod("POST");
  26. // 设置请求头Content-Type
  27. uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
  28. // 获取媒体文件上传的输出流(往微信服务器写数据)
  29. OutputStream outputStream = uploadConn.getOutputStream();
  30. URL mediaUrl = new URL(mediaFileUrl);
  31. HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
  32. meidaConn.setDoOutput(true);
  33. meidaConn.setRequestMethod("GET");
  34. // 从请求头中获取内容类型
  35. String contentType = meidaConn.getHeaderField("Content-Type");
  36. // 根据内容类型判断文件扩展名
  37. String fileExt = WeixinUtil.getFileEndWitsh(contentType);
  38. // 请求体开始
  39. outputStream.write(("--" + boundary + "\r\n").getBytes());
  40. outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
  41. outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
  42. // 获取媒体文件的输入流(读取文件)
  43. BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
  44. byte[] buf = new byte[8096];
  45. int size = 0;
  46. while ((size = bis.read(buf)) != -1) {
  47. // 将媒体文件写到输出流(往微信服务器写数据)
  48. outputStream.write(buf, 0, size);
  49. }
  50. // 请求体结束
  51. outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
  52. outputStream.close();
  53. bis.close();
  54. meidaConn.disconnect();
  55. // 获取媒体文件上传的输入流(从微信服务器读数据)
  56. InputStream inputStream = uploadConn.getInputStream();
  57. InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
  58. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  59. StringBuffer buffer = new StringBuffer();
  60. String str = null;
  61. while ((str = bufferedReader.readLine()) != null) {
  62. buffer.append(str);
  63. }
  64. bufferedReader.close();
  65. inputStreamReader.close();
  66. // 释放资源
  67. inputStream.close();
  68. inputStream = null;
  69. uploadConn.disconnect();
  70. // 使用JSON-lib解析返回结果
  71. JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
  72. // 测试打印结果
  73. System.out.println("打印测试结果"+jsonObject);
  74. weixinMedia = new WeixinMedia();
  75. weixinMedia.setType(jsonObject.getString("type"));
  76. // type等于 缩略图(thumb) 时的返回结果和其它类型不一样
  77. if ("thumb".equals(type))
  78. weixinMedia.setMediaId(jsonObject.getString("thumb_media_id"));
  79. else
  80. weixinMedia.setMediaId(jsonObject.getString("media_id"));
  81. weixinMedia.setCreatedAt(jsonObject.getInt("created_at"));
  82. } catch (Exception e) {
  83. weixinMedia = null;
  84. String error = String.format("上传媒体文件失败:%s", e);
  85. System.out.println(error);
  86. }
  87. return weixinMedia;
  88. }

下载媒体文件:

 

 

[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. if (!savePath.endsWith("/")) {
  19. savePath += "/";
  20. }
  21. // 根据内容类型获取扩展名
  22. String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
  23. // 将mediaId作为文件名
  24. filePath = savePath + mediaId + fileExt;
  25. BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
  26. FileOutputStream fos = new FileOutputStream(new File(filePath));
  27. byte[] buf = new byte[8096];
  28. int size = 0;
  29. while ((size = bis.read(buf)) != -1)
  30. fos.write(buf, 0, size);
  31. fos.close();
  32. bis.close();
  33. conn.disconnect();
  34. String info = String.format("下载媒体文件成功,filePath=" + filePath);
  35. System.out.println(info);
  36. } catch (Exception e) {
  37. filePath = null;
  38. String error = String.format("下载媒体文件失败:%s", e);
  39. System.out.println(error);
  40. }
  41. return filePath;
  42. }

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. System.out.println("分割线*******************************************************************************************");
  22. /**
  23. * 下载多媒体文件
  24. */
  25. String savePath = downloadMedia(access_token, weixinMedia.getMediaId(), "E:/download");
  26. System.out.println("下载成功之后保存在本地的地址为:"+savePath);
  27. }

本地测试打印结果图:

 

 

下载成功之后保存到本地的图片地址图片:

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。