简介:
前端调用拍照或者录音等接口完成后会获取到微信返回的serverId(mediaId),将mediaId传给后端,后端就可以拿着该id调用微信的临时素材接口下载所需的素材。
依赖:
<!-- 文件格式转换依赖 -->
<!-- https://mvnrepository.com/artifact/ws.schild/jave-core -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-core</artifactId>
<version>2.4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-mock -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ws.schild/jave-native-win64 Windows版本-->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-native-win64</artifactId>
<version>2.4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ws.schild/jave-native-linux64 Linux版本-->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-native-linux64</artifactId>
<version>2.4.4</version>
</dependency>
工具类(下载素材及获取Token类):
package com.ruoyi.project.mobile.utils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import ws.schild.jave.AudioAttributes;
import ws.schild.jave.Encoder;
import ws.schild.jave.EncodingAttributes;
import ws.schild.jave.MultimediaObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
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 ("image/png".equals(contentType))
fileEndWitsh = ".png";
else if ("image/jpg".equals(contentType))
fileEndWitsh = ".jpg";
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 savePath 文件在服务器上的存储路径
* */
public static String downloadMedia(String accessToken, String mediaId, String savePath) {
String filePath = null;
String fileExt = null;
// 拼接请求地址
String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID&debug=1";
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 += "/";
}
// 根据内容类型获取扩展名
fileExt = 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);
} catch (Exception e) {
filePath = null;
String error = String.format("下载媒体文件失败:%s", e);
}
String newPath = null;
if(filePath.contains(".amr")) {
newPath = savePath + mediaId + ".mp3";
formatConversion(filePath,newPath);
return "/profile" + "/mobile/" + mediaId + ".mp3";
}
return "/profile" + "/mobile/" + mediaId + fileExt;
}
/**
* 文件格式转换
*
* @return
*/
public static MultipartFile formatConversion(String resourcePath,String targetPath) {
MockMultipartFile mockMultipartFile = null;
try {
File source = new File(resourcePath);
File target = new File(targetPath);
//Audio Attributes
AudioAttributes audio = new AudioAttributes();
audio.setCodec("libmp3lame");
audio.setBitRate(128000);
audio.setChannels(2);
audio.setSamplingRate(44100);
//Encoding attributes
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
attrs.setAudioAttributes(audio);
//Encode
Encoder encoder = new Encoder();
encoder.encode(new MultimediaObject(source), target, attrs);
//转MultipartFile
FileInputStream fileInputStream = new FileInputStream(target);
mockMultipartFile = new MockMultipartFile(target.getName(), fileInputStream);
System.out.println("转换完成");
} catch (Exception ex) {
System.out.println("转换失败");
ex.printStackTrace();
}
return mockMultipartFile;
}
}
package com.ruoyi.project.mobile.utils;
import static java.lang.Thread.sleep;
import net.sf.json.JSONObject;
public class GetToken {
public static String getAccseeToken() throws Exception {
String access_tocken = null;
//访问地址
String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//appid
String APPID = "xxxxxxxxx";
//appsecret
String APPSECRET = "xxxxxxxxxxx";
String request_url = TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
HttpsUtil httpsUtil = new HttpsUtil();
System.out.println(request_url);
int i = 0;
JSONObject jsonObject = httpsUtil.HttpsUtil(request_url,"GET",null);
if(null != jsonObject){
access_tocken = jsonObject.getString("access_token");
String expires_in = jsonObject.getString("expires_in");
//获取到的access_tocken值可以写入到文本文件中供其他业务逻辑调用,实例中只打印了没有保存到文件
System.out.println("获取成功"+"access_tocken="+access_tocken+"||expires_in="+expires_in);
i=Integer.parseInt(expires_in);
}
return access_tocken;
}
}
使用:
@GetMapping("/downloadWxFiles")
@ResponseBody
public String downloadWxFiles(String mediaId) {
/**
* 下载多媒体文件
*/
String token = null;
try {
token = GetToken.getAccseeToken();
} catch (Exception e) {
e.printStackTrace();
}
String savePath = DloadImgUtil.downloadMedia(token, mediaId, "/home/hb/uploadPath/mobile/");
System.out.println("录音路径:" + savePath);
if(!StringUtils.contains(savePath,".")) {
return "error";
}
return savePath;
}