- 保存音频并转换格式(转换音频另一篇内容)
public class FileUpload {
public static String uploadFile(MultipartFile file,String questionId ,String userId, HttpServletRequest request) throws IOException {
String fileName = file.getOriginalFilename();
String suff= fileName.substring(fileName.lastIndexOf("."), fileName.length());
fileName = questionId+userId+suff;
String filePath = Util.getProperty("uploadFile", "filePath");
File tempFile = new File(filePath, String.valueOf(fileName));
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdir();
}
if (!tempFile.exists()) {
tempFile.createNewFile();
}else{
tempFile.delete();
}
file.transferTo(tempFile);
return tempFile.getName();
}
public static void deleteFile(String fileName , HttpServletRequest request) throws IOException {
String filePath = Util.getProperty("uploadFile", "filePath");
File tempFile = new File(filePath, String.valueOf(fileName));
if (tempFile.exists()) {
tempFile.delete();
}
}
}
/**
* 根据题目ID和用户ID保存语音文件并更新记录
* @param file
* @param questionId
* @param userId
* @throws Exception
*/
public void uploadFile(MultipartFile file, String questionId, String userId ,HttpServletRequest request) throws Exception {
if(!file.isEmpty()){
ExaminationScoreExample example = new ExaminationScoreExample();
example.createCriteria().andExaminationQuestionsIdEqualTo(Integer.valueOf(questionId)).andUserIdEqualTo(Integer.valueOf(userId));
List<ExaminationScore> examinationScoreList = examinationScoreMapper.selectByExample(example);
if(examinationScoreList != null && examinationScoreList.size() > 0){
if(examinationScoreList.get(0)!=null && examinationScoreList.get(0).getAudioPath()!=null){
FileUpload.deleteFile( examinationScoreList.get(0).getAudioPath(), request);
}
String filePath = FileUpload.uploadFile(file,questionId,userId+System.currentTimeMillis(), request);
logger.info("filePath:" + filePath);
String wavFilePath= filePath.substring(0,filePath.lastIndexOf("."))+".wav";
String parentPath = Util.getProperty("uploadFile", "filePath");
PCM2WAV.convertAudioFiles(parentPath+filePath, parentPath+wavFilePath);
FileUpload.deleteFile( filePath, request);
ExaminationScore examinationScore = new ExaminationScore();
examinationScore.setId(examinationScoreList.get(0).getId());
examinationScore.setAudioPath(wavFilePath);
examinationScore.setUpdateTime(new Date());
examinationScoreMapper.updateByPrimaryKeySelective(examinationScore);
}
}
}