Prechádzať zdrojové kódy

上传文件删除临时文件

lyhzzz 3 rokov pred
rodič
commit
d8e71e31ac

+ 6 - 0
pom.xml

@@ -93,6 +93,12 @@
             <version>1.18.20</version>
         </dependency>
 
+        <dependency>
+            <groupId>org.bytedeco</groupId>
+            <artifactId>ffmpeg</artifactId>
+            <version>4.3.1-1.5.4</version>
+        </dependency>
+
     </dependencies>
 
     <build>

+ 2 - 0
src/main/java/com/fdkankan/fusion/common/FilePath.java

@@ -10,5 +10,7 @@ public class FilePath {
 
     public final static String VIDEO_OSS_PATH = "fusion/video/%s";
 
+    public final static String VIDEO_LOCAL_PATH = "/home/fusion/video/merge";
+
 
 }

+ 69 - 0
src/main/java/com/fdkankan/fusion/common/util/VideoUtil.java

@@ -0,0 +1,69 @@
+package com.fdkankan.fusion.common.util;
+
+import org.apache.commons.lang3.StringUtils;
+import org.bytedeco.ffmpeg.avcodec.AVPacket;
+import org.bytedeco.ffmpeg.global.avcodec;
+import org.bytedeco.ffmpeg.global.avutil;
+import org.bytedeco.javacv.FFmpegFrameGrabber;
+import org.bytedeco.javacv.FFmpegFrameRecorder;
+import org.bytedeco.javacv.Frame;
+
+import java.io.*;
+import java.util.*;
+
+public class VideoUtil {
+
+    /**
+     *  多个视频的合并
+     * @param videoAddrSet  地址集合
+     * @param output  合并后的视频输出地址
+     */
+    public static String videoMerge(LinkedHashSet<String> videoAddrSet, String output)
+            throws org.bytedeco.javacv.FrameRecorder.Exception, org.bytedeco.javacv.FrameGrabber.Exception {
+        File tagFile = new File(output);
+        if(!tagFile.exists()){
+            tagFile.mkdirs();
+        }
+        output +="/"+ UUID.randomUUID().toString().replace("-","")+".mp4";
+
+        List<String> videoList = new ArrayList<>(videoAddrSet);
+
+        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(videoList.get(0));
+        grabber.start();
+
+        FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(output, grabber.getImageWidth(),
+                grabber.getImageHeight(), 0);
+        recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
+//		recorder.setAudioChannels(1);
+//		recorder.setInterleaved(true);
+        recorder.setFormat("mp4");
+        recorder.setFrameRate(grabber.getFrameRate());
+        recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P); // yuv420p
+        int bitrate = grabber.getVideoBitrate();
+        if (bitrate == 0) {
+            bitrate = grabber.getAudioBitrate();
+        }
+        recorder.setVideoBitrate(bitrate);
+
+        recorder.start();
+        Frame frame = null;
+        for (; (frame = grabber.grabImage()) != null;) {
+            // 封装/复用
+            recorder.record(frame);
+        }
+        for(int i=1;i<videoList.size();i++) {
+            FFmpegFrameGrabber grabberTemp = new FFmpegFrameGrabber(videoList.get(i));
+            grabberTemp.start();
+            for (; (frame = grabberTemp.grabImage()) != null;) {
+                // 封装/复用
+                recorder.record(frame);
+            }
+            grabberTemp.close();
+        }
+
+        recorder.close();
+        grabber.close();
+        return output;
+    }
+
+}

+ 1 - 1
src/main/java/com/fdkankan/fusion/controller/HotIconController.java

@@ -44,7 +44,7 @@ public class HotIconController {
 
     @PostMapping("/add")
     public ResultData add(@RequestParam(required = false) MultipartFile file, @RequestHeader String token) throws IOException {
-        String iconUrl = uploadService.uploadFile(file, true, "icon/");
+        String iconUrl = uploadService.uploadFile(file, true, "icon/",null);
 
         String username = JwtUtil.getUsername(token);
         HotIcon hotIcon = new HotIcon();

+ 1 - 1
src/main/java/com/fdkankan/fusion/controller/UploadController.java

@@ -30,6 +30,6 @@ public class UploadController {
     @PostMapping("/file")
     public ResultData file(@RequestParam(required = false) MultipartFile file) throws Exception {
 
-        return ResultData.ok( uploadService.uploadFile(file,true,"file/"));
+        return ResultData.ok( uploadService.uploadFile(file,true,"file/",null));
     }
 }

+ 5 - 1
src/main/java/com/fdkankan/fusion/service/impl/CaseNumServiceImpl.java

@@ -94,6 +94,9 @@ public class CaseNumServiceImpl extends ServiceImpl<ICaseNumMapper, CaseNumEntit
             String objPath = String.format(OBJ_PATH ,num);
             String glbPath = String.format(GLB_PATH,num) +"/mesh.glb";
             String glbOssPath = String.format(FilePath.GLB_OSS_PATH , num);
+            if(uploadToOssUtil.existKey(glbOssPath)){
+                return queryPath + "/"+glbOssPath;
+            }
             List<String> fileList = uploadToOssUtil.listKeysFromAli(String.format(FilePath.OBJ_OSS_PATH, num));
             for (String fileName : fileList) {
                 File file = new File(objPath);
@@ -103,9 +106,10 @@ public class CaseNumServiceImpl extends ServiceImpl<ICaseNumMapper, CaseNumEntit
                 String[] split = fileName.split("/");
                 uploadToOssUtil.downFormAli(fileName,objPath +"/"+split[split.length-1]);
             }
-
             OBJToGLBUtil.objToGlb(objPath,glbPath );
             uploadToOssUtil.upload(glbPath,glbOssPath);
+            File file = new File(objPath);
+            file.deleteOnExit();
             return queryPath + "/"+glbOssPath;
         }
         return null;

+ 9 - 1
src/main/java/com/fdkankan/fusion/service/impl/CaseVideoServiceImpl.java

@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.fdkankan.common.constant.ErrorCode;
 import com.fdkankan.fusion.common.FilePath;
 import com.fdkankan.fusion.common.ResultCode;
+import com.fdkankan.fusion.common.util.VideoUtil;
 import com.fdkankan.fusion.entity.CaseEntity;
 import com.fdkankan.fusion.entity.CaseVideoFolder;
 import com.fdkankan.fusion.exception.BusinessException;
@@ -23,9 +24,11 @@ import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 import org.springframework.web.multipart.MultipartFile;
 
+import java.io.File;
 import java.io.IOException;
 import java.lang.reflect.Field;
 import java.util.ArrayList;
+import java.util.LinkedHashSet;
 import java.util.List;
 
 /**
@@ -81,8 +84,9 @@ public class CaseVideoServiceImpl extends ServiceImpl<ICaseVideoMapper, CaseVide
         this.deleteByFolderId(folderId);
         List<CaseVideo> videoList = new ArrayList<>();
         Integer sort = 1;
+        LinkedHashSet<String> filePath = new LinkedHashSet<>();
         for (MultipartFile file : files) {
-            String ossPath = uploadService.uploadFile(file, true, String.format(FilePath.VIDEO_OSS_PATH,videoFolder.getVideoFolderId()));
+            String ossPath = uploadService.uploadFile(file, true, String.format(FilePath.VIDEO_OSS_PATH,videoFolder.getVideoFolderId()),filePath);
             CaseVideo caseVideo = new CaseVideo();
             caseVideo.setFolderId(videoFolder.getVideoFolderId());
             caseVideo.setVideoPath(ossPath);
@@ -92,6 +96,10 @@ public class CaseVideoServiceImpl extends ServiceImpl<ICaseVideoMapper, CaseVide
             sort ++;
         }
         this.saveBatch(videoList);
+        String mergeLocalPath = VideoUtil.videoMerge(filePath, FilePath.VIDEO_LOCAL_PATH);
+        uploadToOssUtil.upload(mergeLocalPath,String.format(FilePath.VIDEO_OSS_PATH,videoFolder.getVideoFolderId()));
+        File file = new File(mergeLocalPath);
+        file.deleteOnExit();
     }
 
 

+ 6 - 1
src/main/java/com/fdkankan/fusion/service/impl/ModelServiceImpl.java

@@ -83,6 +83,7 @@ public class ModelServiceImpl extends ServiceImpl<IModelMapper, Model> implement
         model.setModelSize(file.getSize());
         model.setUserName(username);
         this.save(model);
+        File newObjFile = null;
         try {
             String objPath = String.format(OBJ_PATH , "modelId_"+model.getModelId());
             String glbPath = String.format(GLB_PATH , "modelId_"+model.getModelId()) +"/"+modelName +"/mesh.glb";
@@ -90,7 +91,7 @@ public class ModelServiceImpl extends ServiceImpl<IModelMapper, Model> implement
             model.setModelObjUrl(objPath);
             model.setModelGlbUrl(queryPath + glbOssPath);
 
-            File newObjFile = new File(objPath +"/" + fileName);
+            newObjFile = new File(objPath +"/" + fileName);
             if(!newObjFile.getParentFile().exists()){
                 newObjFile.mkdirs();
             }
@@ -112,6 +113,10 @@ public class ModelServiceImpl extends ServiceImpl<IModelMapper, Model> implement
             this.updateById(model);
             e.printStackTrace();
             throw e;
+        }finally {
+            if(newObjFile!=null){
+                newObjFile.deleteOnExit();
+            }
         }
 
     }

+ 29 - 15
src/main/java/com/fdkankan/fusion/service/impl/UploadService.java

@@ -11,6 +11,7 @@ import org.springframework.web.multipart.MultipartFile;
 import javax.annotation.Resource;
 import java.io.File;
 import java.io.IOException;
+import java.util.LinkedHashSet;
 import java.util.UUID;
 
 @Service
@@ -24,7 +25,7 @@ public class UploadService {
     @Value("${upload.query-path}")
     private String queryPath;
 
-    public String uploadFile(MultipartFile file, boolean newName, String filePathAdd) throws IOException {
+    public String uploadFile(MultipartFile file, boolean newName, String filePathAdd, LinkedHashSet<String> filePath) {
         if(file.isEmpty()){
             throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST);
         }
@@ -37,21 +38,34 @@ public class UploadService {
         if(StringUtils.isEmpty(fileName)){
             throw new BusinessException(ResultCode.UPLOAD_FILE_NO_EXIST);
         }
-        //获取文件后缀名
-        String suffixName = fileName.substring(fileName.lastIndexOf("."));
-        //重新生成文件名
-        if(newName){
-            fileName = UUID.randomUUID().toString().replace("-","") + suffixName;
-        }else {
-            fileName= fileName.substring(0,fileName.lastIndexOf("."));
-        }
-        File localFile = File.createTempFile(fileName,suffixName);
-        file.transferTo(localFile);
-        String path = localFile.getPath();
-        uploadToOssUtil.upload(path,filePath +filePathAdd+ fileName + suffixName);
-        if(!uploadToOssUtil.existKey(filePath +filePathAdd + fileName + suffixName)){
+        File localFile = null;
+        try {
+            //获取文件后缀名
+            String suffixName = fileName.substring(fileName.lastIndexOf("."));
+            //重新生成文件名
+            if(newName){
+                fileName = UUID.randomUUID().toString().replace("-","") + suffixName;
+            }else {
+                fileName= fileName.substring(0,fileName.lastIndexOf("."));
+            }
+            localFile = File.createTempFile(fileName,suffixName);
+            file.transferTo(localFile);
+            String path = localFile.getPath();
+            if(filePath !=null){
+                filePath.add(path);
+            }
+            uploadToOssUtil.upload(path,filePath +filePathAdd+ fileName + suffixName);
+            if(!uploadToOssUtil.existKey(filePath +filePathAdd + fileName + suffixName)){
+                throw new BusinessException(ResultCode.UPLOAD_ERROR.code,ResultCode.UPLOAD_ERROR.msg);
+            }
+            return queryPath + filePath +filePathAdd+ fileName + suffixName;
+        }catch (Exception e){
             throw new BusinessException(ResultCode.UPLOAD_ERROR.code,ResultCode.UPLOAD_ERROR.msg);
+        }finally {
+            if(localFile!=null){
+                localFile.deleteOnExit();   //删除临时文件
+            }
         }
-        return queryPath + filePath +filePathAdd+ fileName + suffixName;
+
     }
 }