*
* 根据文件id获取文件流
* @param mediaId
* 媒体id
* @throws Exception
*/
public static InputStream getInputStream(String mediaId) {
String accessToken=TaskController.getAccessToken();
InputStream is = null;
String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
+ accessToken + "&media_id=" + mediaId;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet
.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
http.connect();
// 获取文件转化为byte流
is = http.getInputStream();
System.out.println("文件流======:"+is);
} catch (Exception e) {
e.printStackTrace();
}
return is;
}
/**
*
* 创建文件路径和文件名称
*/ private String getFilePath() {
String baseFolder = propertieService.REPOSITORY_PATH+File.separator + "images";
Date nowDate = new Date();
// yyyy/MM/dd
String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy")
+ File.separator + new DateTime(nowDate).toString("MM") + File.separator
+ new DateTime(nowDate).toString("dd");
File file = new File(fileFolder);
if (!file.isDirectory()) {
// 如果目录不存在,则创建目录
file.mkdirs();
}
// 生成新的文件名
//String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
// + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
// 生成新的文件名--微信下载的文件格式为amr
String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
+ RandomUtils.nextInt(100, 9999) + "." + "amr";
return fileFolder + File.separator + fileName;
}
/**
*
* 获取下载文件信息,保存到磁盘
* @param mediaId
* 文件的id
* @throws Exception
*/
@ResponseBody
@RequestMapping(value="downAndupload",method=RequestMethod.GET)
public String saveToDisk(String mediaId){
//public String saveToDisk(String mediaId)throws Exception {
InputStream inputStream = getInputStream(mediaId);
FileOutputStream fileOutputStream = null;
int size=0;
try {
size = inputStream.available();
byte[] data = new byte[size];
int len = 0;
// 文件新路径
String filePath = getFilePath();
// 生成图片的绝对引用地址
// 封装Result对象,并且将文件的byte数组放置到result对象中
PicUploadResult fileUploadResult = new PicUploadResult();
String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath, propertieService.REPOSITORY_PATH), "\\", "/");
fileUploadResult.setUrl(propertieService.IMAGE_BASE_URL + picUrl);
fileOutputStream = new FileOutputStream(filePath);
while ((len = inputStream.read(data)) != -1) {
fileOutputStream.write(data, 0, len);
//String url=convertAmr2Mp3(fileUploadResult.getUrl());
String url=convertAmr2Mp3(propertieService.REPOSITORY_PATH+picUrl);
//return fileUploadResult.getUrl();
String wavUrl = StringUtils.replace(StringUtils.substringAfter(url, propertieService.REPOSITORY_PATH), "\\", "/");
return propertieService.IMAGE_BASE_URL+wavUrl;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
//从微信下载下来的文件格式是amr格式的,amr的文件比较小,下载下来后可以在手机上播放,但是不能通话html标签进行播放,因此将其转为wav或者mp3才能在html里面播放,下面贴出转为wav格式文件的代码,转为mp3的与此相似,但是我没有转成功,有转为成功的可赐教。
/**
* 将amr格式转为wav格式
* @param amrFilePath amr文件
* @return wav文件路径
*/
public static String convertAmr2Mp3(String amrFilePath) {
File source = new File(amrFilePath);
String extension = amrFilePath.substring(amrFilePath.lastIndexOf("."));
String targetFilename = amrFilePath.replace(extension, ".wav");
String os = System.getProperties().getProperty("os.name").toLowerCase();
if (os.startsWith("win")) {
File target = new File(targetFilename);
Encoder encoder = new Encoder();
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
AudioAttributes audio = new AudioAttributes();
audio.setCodec("libmp3lame");
attrs.setAudioAttributes(audio);
try {
encoder.encode(source, target, attrs);
} catch (Exception e) {
e.printStackTrace();
LOGGER.debug("win convert amr to wav error", e.getMessage());
}
} else {
String command = "ffmpeg -i " + amrFilePath + " "+ targetFilename;
try {
Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
LOGGER.debug("linux convert amr to wav error", e.getMessage());
}
}
return targetFilename;
}