在SpringBoot專案中實作視頻的上傳和下載,地址都是存放至阿里云的,但是由于視頻數量越來越多占用的記憶體也越來越大,導致服務器記憶體不足,公司為了減少服務器開支,要求我們研發人員把最好把記憶體利用到極致,盡量減少不必要的浪費,所以就需要把視頻進行壓縮,
上傳前要先下載ffmpeg軟體,這個軟體會執行壓縮命令,百度上可搜索到直接下載

一、定義視頻上傳請求介面
public AjaxResult videoUploadFile(MultipartFile file){
try {
if(null == file || file.isEmpty()){
return AjaxResult.error("檔案為空");
}
String ossFilePrefix = StringUtils.genUUID();
String fileName = ossFilePrefix +"-"+ file.getOriginalFilename();
String fileurl = AliOssUtils.videoUploadFile(file,fileName);
AjaxResult ajax = AjaxResult.success();
ajax.put("fileName", "after_"+fileName);
ajax.put("url", fileurl);
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
二、視頻暫存至本地檔案夾
public static final String uploadVideo(String baseDir, MultipartFile file, String fileName) throws FileSizeLimitExceededException, IOException {
File desc = getAbsoluteFile(baseDir, fileName);
file.transferTo(desc);
String pathFileName = getPathFileName(baseDir, fileName);
return pathFileName;
}
三、開始壓縮視頻
public static boolean toCompressFile(String convertFile,String targetFile){
try{
/**將視頻壓縮為 每秒15幀 平均碼率600k 畫面的寬與高 為1280*720*/
String cutCmd="ffmpeg -i " + convertFile + " -r 15 -b:v 600k -s 1280x720 "+ targetFile;
log.info("cutCmd: " + cutCmd);
runCmd(cutCmd);
log.info("檔案:"+convertFile+" 視屏壓縮完成");
}catch(Exception e){
e.printStackTrace();
log.info("壓縮檔案出現例外:"+e.getMessage());
return false;
}
return true;
}
四、上傳至阿里云并獲取壓縮后的視頻路徑
private static String getFileUrl(String path) throws IOException {
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
MultipartFile multipartFile1 = new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
uploadFile(multipartFile1, file.getName());
String url = getUrl(file.getName());
return url;
}
五、核心呼叫
public static String videoUploadFile(MultipartFile multipartFile, String fileName) throws IOException {
//存放路徑
String filePath = FileUploadUtils.uploadVideo(getDefaultBaseDir(), multipartFile, fileName);
String convertFile = filePath.replace("/profile", getDefaultBaseDir()).replaceAll("//", "/");
//字串第一個字符最后出現的下標
int lastIndex = convertFile.lastIndexOf("/");
StringBuilder sb = new StringBuilder(convertFile);
String convertFile1 = sb.insert(lastIndex + 1, "after_").toString();
boolean flag = toCompressFile(convertFile, convertFile1);
if (!flag) {
throw new CustomException("檔案壓縮出現例外");
}
//讀取壓縮后的檔案并上傳至阿里云
String url = getFileUrl(convertFile1);
//洗掉本地暫存檔案
FileUtils.deleteFile(convertFile);
log.info("檔案:" + convertFile + " 洗掉成功");
FileUtils.deleteFile(convertFile1);
log.info("檔案:" + convertFile1 + " 洗掉成功");
return url;
}
六、spring boot的yml組態檔
修改application.yml檔案:
spring:
servlet:
mvc:
async:
request-timeout: 2000000
修改application-prd.yml檔案:
spring:
servlet:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
視頻上傳至阿里云這一塊代碼沒有貼出來,每個專案都大同小異,可根據自己專案實際情況做調整,這篇最核心的是視頻壓縮的方法及思路,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/545683.html
標籤:Java
