前台通过ajaxfileupload插件上传提价数据:
$.ajaxFileUpload({
url : "${ctx}/h5/h5preventiveEdu/updateEdu",//增加与修改通用
secureuri : false,
fileElementId : elementId,
dataType:'text/html',
async : false,
data : {
name : elementId,
fileds : elementId,
optType : obj['optType'],
title : obj['title'],
content : obj['content'].replace(/[\n\r]/g, "<br>").replace(/<br><br>/g,"<br>"),
id : preventiveEduId
},
success : function(data, status) {
$this.removeData("ajax");
if(opt == 'add'){
swal({title:"", text:"成功!请等待后台视频处理", confirmButtonText:"确定"});
}
window.location.href = "${ctx}/h5/h5preventiveEdu/police/preventiveEdu";
},
error : function(data, status, e) {
$this.removeData("ajax");
}
});
后台处理
/**
* @Description: 增加\修改 防范教育*/
@RequestMapping(value = "/updateEdu", method = { RequestMethod.GET, RequestMethod.POST })
public String updateEdu(HttpServletRequest req, HttpServletResponse response, MultipartHttpServletRequest rt,
Model model) {
StringBuffer str = new StringBuffer("");
H5User user = (H5User) SecurityUtils.getSubject().getPrincipal();
String pic = "";
String fileName = "";
String attFile = "";
// 封装防范教育信息
PreventiveEdu voPe = new PreventiveEdu();
PreventiveEduAttachment voPea = new PreventiveEduAttachment();
voPe.setTitle(req.getParameter("title"));
voPe.setContent(req.getParameter("content"));
voPe.setCreateUser(user.getId());
voPe.setCreateTime(new Date());
voPe.setEcid(user.getEcId());
try {
String file_path = BaseConstant.PREVENTIVE_EDU_FILE_PATH + StringUtil.getCurrDateStr() + "/";
//图片格式
String fileRegx = StringUtil.getReg(BaseConstant.STUDY_CORNER_VEDIO_EXT, true);
// 大小限制
//long imgFileMaxSize = BaseConstant.NOTICE_IMAGE_FILE_SIZE;
MultipartFile patch = rt.getFile(req.getParameter("name"));// 获取文件
if (patch != null && !patch.isEmpty()) {
attFile = patch.getOriginalFilename();// 得到实际文件名
String currTime = String.valueOf(System.currentTimeMillis());
if (attFile != "") {
fileName = StringUtil.getCurrDateStr() + "/" + currTime
+ attFile.substring(attFile.lastIndexOf("."));
}
if (!patch.isEmpty()) {
File saveDir = new File(file_path);
if (!saveDir.exists()) {
saveDir.mkdirs();
}
pic = BaseConstant.PREVENTIVE_EDU_FILE_URL + fileName;
if (!fileName.matches(fileRegx)) {
// 资源图片文件格式非法
str.append("操作失败:附件格式不正确,请上传" + BaseConstant.STUDY_CORNER_VEDIO_EXT + "格式的文件");
req.setAttribute("msg", str.toString());
return getAllPreventiveEdu(1, null, model);
}
File localFile = new File(file_path + currTime + attFile.substring(attFile.lastIndexOf(".")));
log.info("视频存放位置:" + localFile.getAbsolutePath());
patch.transferTo(localFile);
log.info("视频访问地址:" + pic);
voPea.setDisName(attFile);
voPea.setFileName(fileName);
voPea.setFileSize(patch.getSize());
voPea.setFileType(attFile.substring(attFile.lastIndexOf(".")+1));
voPea.setAttType(4L);
voPea.setCreateUser(user.getId());
voPea.setCreateTime(new Date());
Encoder encoder = new Encoder();
try {
MultimediaInfo m = encoder.getInfo(localFile);
long ls = m.getDuration();
//取得播放时长,毫秒为单位
voPea.setPlayLength(ls);
} catch (Exception e) {
e.printStackTrace();
}
voPe.setVideoname(attFile);
voPe.setVideourl(fileName);
}
}
else {
voPea = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
String optType = req.getParameter("optType");
if (optType.equalsIgnoreCase("edit")) {
voPe.setId(Long.parseLong(req.getParameter("id")));
}
String msg = preventiveEduService.updatePreventiveEdu(voPe,voPea, req.getParameter("optType"));
req.setAttribute("msg", msg);
if (!StringUtil.isEmptyOrNull(voPe.getVideourl())){
//进行转码
videoEncodeProducer.sendToQueue(1, voPe.getVideourl(), voPe.getId());
}
return getAllPreventiveEdu(1, null, model);
}
//转码关键代码
@Override
public void videoEncode(Map<String, Object> temp) {
if (temp != null){
int type = (int) temp.get("type");
String videoURL = (String) temp.get("videoURL");
Long id = (Long) temp.get("id");
if (type == 1){//防范教育的视频
File source = new File(BaseConstant.PREVENTIVE_EDU_FILE_PATH + videoURL);
String targetFileName = StringUtil.getCurrDateStr() + "/" + System.currentTimeMillis() + ".mp4";
File target = new File(BaseConstant.PREVENTIVE_EDU_FILE_PATH + targetFileName);
boolean success = encode(source, target);
if (success){
//更新防范教育表视频地址
PreventiveEdu pe = new PreventiveEdu();
pe.setId(id);
pe.setVideourl(targetFileName);
preventiveEduMapper.updateByPrimaryKeySelective(pe);
}
}
}
}
public boolean encode(File source, File target) {
AudioAttributes audio = new AudioAttributes();
audio.setCodec("aac");
VideoAttributes video = new VideoAttributes();
video.setCodec("h264");
video.setBitRate(new Integer(160000));
// video.setFrameRate(new Integer(15));
video.setSize(new VideoSize(480, 360));
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp4");
attrs.setAudioAttributes(audio);
attrs.setVideoAttributes(video);
Encoder encoder = new Encoder();
try {
encoder.encode(source, target, attrs);
} catch (IllegalArgumentException | EncoderException e) {
log.error("视频转码失败", e);
return false;
}
return true;
}