packageclub.openedu.resource.controller;importorg.apache.commons.codec.digest.DigestUtils;importorg.apache.commons.io.FileUtils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.multipart.MultipartFile;importorg.springframework.web.multipart.MultipartHttpServletRequest;importorg.springframework.web.multipart.commons.CommonsMultipartResolver;importclub.openedu.core.controller.BaseController;importclub.openedu.core.dao.OpenDao;importclub.openedu.resource.util.CapturePdfFirstPageUtil;importclub.openedu.resource.util.ConverterUtil;importclub.openedu.resource.util.ImageCutUtil;importclub.openedu.resource.util.VideoCoverMp4Util;importclub.openedu.resource.util.VideoCutUtil;importclub.openedu.resource.vo.MultipartFileParam;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.RandomAccessFile;importjava.util.Iterator;importjava.util.List;importjava.util.Map;importjava.util.UUID;importjava.util.concurrent.atomic.AtomicLong;importjavax.annotation.Resource;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;
@RestControllerpublic class FileUploadController extendsBaseController {
@Resource
OpenDao openDap;publicOpenDao getOpenDap() {returnopenDap;
}public voidsetOpenDap(OpenDao openDap) {this.openDap =openDap;
}
@Value("${server.port}")private intport;
@Value("${web.serverIP}")privateString address;
@Value("${web.upload-path}")privateString uploadPath;
@Value("${syspath.ffmpeg-path}")privateString FFMPEG_PATH;private final static Logger logger= LoggerFactory.getLogger(FileUploadController.class);private static AtomicLong counter = new AtomicLong(0L);
@RequestMapping("uploadfile")public Object uploadv2(MultipartFileParam param) throwsException {//String uploadPath = request.getServletContext().getRealPath( "/" );//uploadPath = uploadPath.replace( "\\", "/" );
Map map =getParameterMap();
String path=null;try{
String prefix= "req_count:" + counter.incrementAndGet() + ":";
logger.info(prefix+ "start !!!");//使用 工具类解析相关参数,工具类代码见下面
logger.info("");
logger.info("");
logger.info("");
logger.info(prefix+ "chunks= " +param.getChunks());
logger.info(prefix+ "chunk= " +param.getChunk());
logger.info(prefix+ "chunkSize= " +param.getSize());//这个必须与前端设定的值一致
long chunkSize = 1024 * 1024;
String finalDirPath= uploadPath + "file/";
logger.info(finalDirPath);
String tempDirPath= finalDirPath +param.getId();
String tempFileName=param.getName();
File confFile= new File(tempDirPath, param.getName() + ".conf");
File tmpDir= newFile(tempDirPath);
File tmpFile= newFile(tempDirPath, tempFileName);if (!tmpDir.exists()) {
tmpDir.mkdirs();
}
RandomAccessFile accessTmpFile= new RandomAccessFile(tmpFile, "rw");
RandomAccessFile accessConfFile= new RandomAccessFile(confFile, "rw");long offset = chunkSize *param.getChunk();//定位到该分片的偏移量
accessTmpFile.seek(offset);//写入该分片数据
accessTmpFile.write(param.getFile().getBytes());//把该分段标记为 true 表示完成
logger.info(prefix + "set part " + param.getChunk() + " complete");
accessConfFile.setLength(param.getChunks());
accessConfFile.seek(param.getChunk());
accessConfFile.write(Byte.MAX_VALUE);//completeList 检查是否全部完成,如果数组里是否全部都是(全部分片都成功上传)
byte[] completeList =FileUtils.readFileToByteArray(confFile);byte isComplete =Byte.MAX_VALUE;for (int i = 0; i < completeList.length && isComplete==Byte.MAX_VALUE; i++) {//与运算, 如果有部分没有完成则 isComplete 不是 Byte.MAX_VALUE
isComplete = (byte)(isComplete &completeList[i]);
logger.info(prefix+ "check part " + i + " complete?:" +completeList[i]);
}if (isComplete ==Byte.MAX_VALUE) {
logger.info(prefix+ "upload complete !!" +
"---------------------------------------------------------");
renameFile(tempDirPath+"/"+tempFileName,tempDirPath+"/"+param.getName());
path="/"+param.getId()+"/"+param.getName();
}
accessTmpFile.close();
accessConfFile.close();
logger.info(prefix+ "end !!!");
}catch(Exception e){
e.printStackTrace();
}/*** 文件上传完成,开始进行格式处理*/
if (path!=null){
logger.info("path!=null ----" + uploadPath+"file"+path);//获取文件MD5
String md5 = DigestUtils.md5Hex(new FileInputStream(uploadPath+"file"+path));//到数据库对比是否存在该文件
map.put("sqlMapId", "getFileIsThisMd5");
map.put("md5", md5);
List> md5List =openDap.queryForList(map);//获取文件类型
String fileType = map.get("type").toString();
String inputFilePath= uploadPath+"file"+path;
String filePath= uploadPath + "file/" +param.getId();
String fileName= map.get("name").toString();int pos = fileName.lastIndexOf(".");
map.put("fileName", fileName.substring(0,pos));
map.put("fileExtName", fileName.substring(pos+1));
map.put("filePath", filePath);
map.put("fileSize", map.get("size").toString());
map.put("resPath", filePath);
map.put("sqlMapId", "saveFileInfo");
String resPk=openDap.insert(map).toString();
map.put("resPk", resPk);if(md5List.size() <= 0){
logger.info("文件不存在,开始处理...");//office文件
if(fileType.contains("doc") || fileType.contains("docx") || fileType.contains("ppt") || fileType.contains("pptx") || fileType.contains("xls") || fileType.contains("xlsx") || fileType.contains("powerpoint")) {//转换HTML、PDF、处理缩略图
ConverterUtil converter = new ConverterUtil(uploadPath+"file"+path);
converter.start();
map.put("pdfName", param.getName() + ".pdf");
map.put("htmlName", param.getName() + ".html");
map.put("imgName", param.getName() + ".jpg");
map.put("sqlMapId", "savePdfOffice");
openDap.insert(map);
map.put("sqlMapId", "saveHtmlOffice");
openDap.insert(map);
map.put("sqlMapId", "saveImgForFile");
openDap.insert(map);
}else if(fileType.contains("image") ) { //图片文件//缩略图处理
ImageCutUtil imgUtil = new ImageCutUtil(inputFilePath, inputFilePath+".jpg", 150);
imgUtil.start();
map.put("imgName", param.getName() + ".jpg");
map.put("sqlMapId", "saveImgForFile");
openDap.insert(map);
}else if(fileType.contains("audio") ) { //音频//设置默认缩略图
}else if(fileType.contains("pdf") ) { //pdf//缩略图处理
String outputFilePath=inputFilePath+".jpg";
CapturePdfFirstPageUtil pdfUtil= new CapturePdfFirstPageUtil(ConverterUtil.getOutputFilePath(inputFilePath,".pdf"), outputFilePath);
pdfUtil.start();
map.put("imgName", param.getName() + ".jpg");
map.put("sqlMapId", "saveImgForFile");
openDap.insert(map);
}else if(fileType.contains("video") ) { //视频
logger.info("进入视频处理……");//截取缩略图
VideoCutUtil videoUtil = new VideoCutUtil(inputFilePath, inputFilePath+".jpg", 2, "450x230",FFMPEG_PATH);
videoUtil.start();
map.put("imgName", param.getName() + ".jpg");
map.put("sqlMapId", "saveImgForFile");
openDap.insert(map);if(fileType.contains("mp4") ) {
logger.info("mp4文件,不做处理");
}else{//转码
VideoCoverMp4Util converter = new VideoCoverMp4Util(uploadPath+"file",path,FFMPEG_PATH);
converter.start();
map.put("mp4Name", param.getName() + ".mp4");
map.put("sqlMapId", "saveMp4ForFile");
openDap.insert(map);
}
}else { //其他
logger.info("其他文件,不做处理");
}
}else{
logger.info("文件已存在");
}
logger.info(uploadPath);
logger.info(path);
logger.info(uploadPath+"file"+path);
String returnPath= address+":"+port+"/file"+path;returnreturnPath;
}return "还在上传中";
}private voidrenameFile(String file, String toFile){
File toBeRenamed= newFile(file);//检查要重命名的文件是否存在,是否是文件
if (!toBeRenamed.exists() ||toBeRenamed.isDirectory()) {
logger.info("File does not exist: " +file);return;
}
File newFile= newFile(toFile);//修改文件名
if(toBeRenamed.renameTo(newFile)) {
logger.info("File has been renamed.");
}else{
logger.info("Error renmaing file");
}
}
@RequestMapping(consumes= "multipart/form-data", value = "/resUpload", method =RequestMethod.POST)public String springUpload(HttpServletRequest request) throwsIllegalStateException, IOException {long startTime =System.currentTimeMillis();
CommonsMultipartResolver multipartResolver= newCommonsMultipartResolver(request.getSession().getServletContext());if(multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest) request;
Iterator iter=multiRequest.getFileNames();
String path= uploadPath + "file/WU_FILE_RES";
File pathFile= newFile(path);if(!pathFile.exists()) {
pathFile.mkdirs();
}
path= path + "/";//上传文件
while(iter.hasNext()) {
MultipartFile file=multiRequest.getFile(iter.next().toString());if (file != null) {
path= path +file.getOriginalFilename();
file.transferTo(newFile(path));
}
String filePath=path ;
String contentType= path.substring(path.lastIndexOf(".")+1);
logger.info("文件格式: " +contentType);
logger.info(contentType.equals("mp4")+"");//office文件
if(contentType.contains("doc") || contentType.contains("docx") || contentType.contains("ppt") || contentType.contains("pptx") || contentType.contains("xls") || contentType.contains("xlsx") || contentType.contains("powerpoint")) {//转换HTML、PDF、处理缩略图
ConverterUtil converter = newConverterUtil(path);
converter.start();
}else if(contentType.contains("pdf") ) { //pdf//缩略图处理
CapturePdfFirstPageUtil pdfUtil= new CapturePdfFirstPageUtil(ConverterUtil.getOutputFilePath(filePath,".pdf"), path+".jpg");
pdfUtil.start();
}else if(contentType.equals("mp4")) { //视频
logger.info("进入视频处理……");
String os= System.getProperty("os.name");if(os.toLowerCase().startsWith("win")){
FFMPEG_PATH= "C:/Program Files/WorkSoftWare/ffmpeg/ffmpeg/bin/ffmpeg.exe";
}else{
FFMPEG_PATH= "/usr/local/ffmpeg/bin/ffmpeg";
}
logger.info("FFMPEG_PATH:" +FFMPEG_PATH);//截取缩略图
VideoCutUtil videoUtil = new VideoCutUtil(filePath, filePath+".jpg", 2, "450x230",FFMPEG_PATH);
videoUtil.start();if(contentType.contains("mp4") ) {
logger.info("mp4文件,不做处理");
}else{//转码
VideoCoverMp4Util converter = new VideoCoverMp4Util(uploadPath+"file",path,FFMPEG_PATH);
converter.start();
}
}else { //其他
logger.info("其他文件,不做处理");
}
}
}long endTime =System.currentTimeMillis();
System.out.println("资源中心文件自动上传处理时间:" + String.valueOf(endTime - startTime) + "ms");return "/success";
}
}