首先是网上下载的工具类,很实用,直接粘贴
/**
* 文件entity
*/
@Data
public class FileEntity {
/**
* 文件類型
*/
private String type;
/**
* 文件大小
*/
private String size;
/**
* 相對路徑
*/
private String path;
/**
* 原始文件名稱(不帶後綴名)
*/
private String titleOrig;
/**
* 新文件名稱 該名稱為當前時間戳(不帶後綴名)
*/
private String titleAlter;
/**
* 上傳時間
*/
private Timestamp uploadTime;
/**
* 絕對路徑
*/
private String absolutePath;
}
上面为文件实体类,只是测试上传功能,并没有考虑数据库的存储,仅供练习用。
public class FileUploadTool {
TransfMediaTool transfMediaTool = new TransfMediaTool();
// 文件最大500M
private static long upload_maxsize = (long) 500 * 1024 * 1024;
// 文件允许格式
private static String[] allowFiles = {".rar", ".doc", ".docx", ".zip",
".pdf", ".txt", ".swf", ".xlsx", ".gif", ".png", ".jpg", ".jpeg",
".bmp", ".xls", ".mp4", ".flv", ".ppt", ".avi", ".mpg", ".wmv",
".3gp", ".mov", ".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb"};
// 允许转码的视频格式(ffmpeg)
private static String[] allowFLV = {".avi", ".mpg", ".wmv", ".3gp",
".mov", ".asf", ".asx", ".vob"};
// 允许的视频转码格式(mencoder)
private static String[] allowAVI = {".wmv9", ".rm", ".rmvb"};
public FileEntity createFile(MultipartFile multipartFile, HttpServletRequest request) throws Exception {
FileEntity entity = new FileEntity();
boolean bflag = false;
//該方法可以獲取上傳文件的名稱 1573628128403.mp4
String fileName = multipartFile.getOriginalFilename().toString();
// 判断文件不为空
if (multipartFile.getSize() != 0 && !multipartFile.isEmpty()) {
bflag = true;
// 判断文件大小 不能大於最高限制
if (multipartFile.getSize() <= upload_maxsize) {
bflag = true;
// 文件类型判断
if (this.checkFileType(fileName)) {
bflag = true;
} else {
bflag = false;
log.error("文件类型不允许");
throw new Exception("文件类型不允许");
}
} else {
bflag = false;
log.error("文件大小超范围");
throw new Exception("文件大小超范围");
}
} else {
bflag = false;
log.error("文件为空");
throw new Exception("文件为空");
}
if (bflag) {
String logoPathDir = "/video/";
// String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);
// 上传到本地磁盘
String logoRealPathDir = "D:/upload";
File logoSaveFile = new File(logoRealPathDir);
if (!logoSaveFile.exists()) {
logoSaveFile.mkdirs();
}
String name = fileName.substring(0, fileName.lastIndexOf("."));
log.info("文件名称:" + name);
// 新的文件名
// String newFileName = this.getName(fileName);
String newFileName = String.valueOf(System.currentTimeMillis());
// 文件扩展名
String fileEnd = this.getFileExt(fileName);
// 绝对路径
String fileNamedirs = logoRealPathDir + File.separator + newFileName + fileEnd;
log.info("保存的绝对路径:" + fileNamedirs);
File filedirs = new File(fileNamedirs);
// 转入文件
try {
multipartFile.transferTo(filedirs);
} catch (IllegalStateException e) {
log.error(e.getMessage());
} catch (IOException e) {
log.error(e.getMessage());
}
// 相对路径
entity.setType(fileEnd);
String fileDir = logoPathDir + newFileName + fileEnd;
StringBuilder builder = new StringBuilder(fileDir);
String finalFileDir = builder.substring(1);
// size存储为String
String size = this.getSize(filedirs);
// 源文件保存路径
String aviPath = filedirs.getAbsolutePath();
// 转码Avi
// boolean flag = false;
if (this.checkAVIType(fileEnd)) {
// 设置转换为AVI格式后文件的保存路径
String codcAviPath = logoRealPathDir + File.separator + newFileName + ".avi";
// 获取配置的转换工具(mencoder.exe)的存放路径
String mencoderPath = request.getSession().getServletContext().getRealPath("/tools/mencoder.exe");
aviPath = transfMediaTool.processAVI(mencoderPath, filedirs.getAbsolutePath(), codcAviPath);
fileEnd = this.getFileExt(codcAviPath);
}
if (aviPath != null) {
// 转码Flv
if (this.checkMediaType(fileEnd)) {
try {
// 设置转换为flv格式后文件的保存路径
String codcFilePath = logoRealPathDir + File.separator + newFileName + ".flv";
// 获取配置的转换工具(ffmpeg.exe)的存放路径
String ffmpegPath = request.getSession().getServletContext().getRealPath("/tools/ffmpeg.exe");
transfMediaTool.processFLV(ffmpegPath, aviPath, codcFilePath);
fileDir = logoPathDir + newFileName + ".flv";
builder = new StringBuilder(fileDir);
finalFileDir = builder.substring(1);
} catch (Exception e) {
log.error(e.getMessage());
}
}
entity.setSize(size);
entity.setPath(finalFileDir);
entity.setTitleOrig(name);
entity.setTitleAlter(newFileName);
entity.setAbsolutePath("http://10.251.134.92:8003/"+newFileName+fileEnd);
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
entity.setUploadTime(timestamp);
return entity;
} else {
throw new Exception("123");
}
} else {
throw new Exception("234");
}
}
/**
* 文件类型判断
*
* @param fileName
* @return
*/
private boolean checkFileType(String fileName) {
Iterator<String> type = Arrays.asList(allowFiles).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileName.toLowerCase().endsWith(ext)) {
return true;
}
}
return false;
}
/**
* 视频类型判断(flv)
*
* @param fileName
* @return
*/
private boolean checkMediaType(String fileEnd) {
Iterator<String> type = Arrays.asList(allowFLV).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileEnd.equals(ext)) {
return true;
}
}
return false;
}
/**
* 视频类型判断(AVI)
*
* @param fileName
* @return
*/
private boolean checkAVIType(String fileEnd) {
Iterator<String> type = Arrays.asList(allowAVI).iterator();
while (type.hasNext()) {
String ext = type.next();
if (fileEnd.equals(ext)) {
return true;
}
}
return false;
}
/**
* 获取文件扩展名
*
* @return string
*/
private String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf("."));
}
/**
* 文件大小,返回kb.mb
*
* @return
*/
private String getSize(File file) {
String size = "";
long fileLength = file.length();
DecimalFormat df = new DecimalFormat("#.00");
if (fileLength < 1024) {
size = df.format((double) fileLength) + "BT";
} else if (fileLength < 1048576) {
size = df.format((double) fileLength / 1024) + "KB";
} else if (fileLength < 1073741824) {
size = df.format((double) fileLength / 1048576) + "MB";
} else {
size = df.format((double) fileLength / 1073741824) + "GB";
}
return size;
}
}
该类为上传的工具类,createFile()方法的作用就是将文件上传到指定服务器硬盘,该方法中声明支持上传的最大文件为500mb,声明了支持上传的文件类型,以及对上传文件的简单判断。
package com.foxconn.util.fileutil;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class TransfMediaTool {
/**
* 视频转码flv
*
* @param ffmpegPath 转码工具的存放路径
* @param upFilePath 用于指定要转换格式的文件,要截图的视频源文件
* @param codcFilePath 格式转换后的的文件保存路径
* @return
* @throws Exception
*/
public void processFLV(String ffmpegPath, String upFilePath, String codcFilePath) {
// 创建一个List集合来保存转换视频文件为flv格式的命令
List<String> convert = new ArrayList<String>();
// 添加转换工具路径
convert.add(ffmpegPath);
// 添加参数"-i",该参数指定要转换的文件
convert.add("-i");
// 添加要转换格式的视频文件的路径
convert.add(upFilePath);
convert.add("-ab");
convert.add("56");
convert.add("-ar");
convert.add("22050");
convert.add("-q:a");
convert.add("8");
convert.add("-r");
convert.add("15");
convert.add("-s");
convert.add("600*500");
/*
* convert.add("-qscale"); // 指定转换的质量 convert.add("6");
* convert.add("-ab"); // 设置音频码率 convert.add("64"); convert.add("-ac");
* // 设置声道数 convert.add("2"); convert.add("-ar"); // 设置声音的采样频率
* convert.add("22050"); convert.add("-r"); // 设置帧频 convert.add("24");
* convert.add("-y"); // 添加参数"-y",该参数指定将覆盖已存在的文件
*/
convert.add(codcFilePath);
try {
Process videoProcess = new ProcessBuilder(convert).redirectErrorStream(true).start();
new PrintStream(videoProcess.getInputStream()).start();
videoProcess.waitFor();
} catch (IOException e1) {
log.error(e1.getMessage());
} catch (InterruptedException e) {
log.error(e.getMessage());
Thread.currentThread().interrupt();
}
}
/**
* 对ffmpeg无法解析的文件格式(wmv9,rm,rmvb等), 先用mencoder转换为avi(ffmpeg能解析的)格式
*
* @param mencoderPath 转码工具的存放路径
* @param upFilePath 用于指定要转换格式的文件,要截图的视频源文件
* @param codcFilePath 格式转换后的的文件保存路径
* @return
* @throws Exception
*/
public String processAVI(String mencoderPath, String upFilePath, String codcAviPath) {
// boolean flag = false;
List<String> commend = new ArrayList<String>();
commend.add(mencoderPath);
commend.add(upFilePath);
commend.add("-oac");
commend.add("mp3lame");
commend.add("-lameopts");
commend.add("preset=64");
commend.add("-lavcopts");
commend.add("acodec=mp3:abitrate=64");
commend.add("-ovc");
commend.add("xvid");
commend.add("-xvidencopts");
commend.add("bitrate=600");
commend.add("-of");
commend.add("avi");
commend.add("-o");
commend.add(codcAviPath);
try {
// 预处理进程
ProcessBuilder builder = new ProcessBuilder();
builder.command(commend);
builder.redirectErrorStream(true);
// 进程信息输出到控制台
Process p = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
log.info(line);
}
p.waitFor();// 直到上面的命令执行完,才向下执行
return codcAviPath;
} catch (Exception e) {
log.error(e.getMessage());
return null;
}
}
}
@Slf4j
class PrintStream extends Thread {
java.io.InputStream __is = null;
public PrintStream(java.io.InputStream is) {
__is = is;
}
@Override
public void run() {
try {
while (this != null) {
int _ch = __is.read();
if (_ch != -1) {
log.info(String.valueOf(_ch));
} else {
break;
}
}
} catch (Exception e) {
log.error(e.getMessage());
}
}
}
该类同样是下载的工具类,没有具体的研究其中的功能,不多做介绍,但是不可或缺。
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
@PostMapping("/uploadFile")
public Object uploadFile(MultipartFile[] multipartFiles, HttpServletRequest request) {
try {
FileUploadTool fileUploadTool = new FileUploadTool();
List<FileEntity> entityList = new ArrayList<>();
for (MultipartFile m : multipartFiles) {
entityList.add(fileUploadTool.createFile(m, request));
}
request.getSession().setAttribute("list", entityList);
return ResultGenerator.genOkResult(entityList);
} catch (Exception e) {
log.error(e.getMessage());
return ResultGenerator.genFailedResult(e.getMessage());
}
}
}
该类微控制器类,可以一次性上传多个文件,返回的类型为封装类,可以直接返回list数据。没有编写前段代码,可以通过postMan来进行测试。
server:
port: 8003
#設置文件最大上傳大小
spring:
servlet:
multipart:
max-file-size: 50MB
max-request-size: 50MB
#設置靜態資源路徑 設置該路徑之後可以直接將圖片或者視頻名稱拼接到項目路徑之後
resources:
static-locations: file:D:\upload
mvc:
static-path-pattern: /**
以上是application.yml文件的配置
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>springboot-CSD</groupId>
<artifactId>springboot-CSD</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
<!-- 热部署 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>-->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<resources>
<resource>
<directory>src/main/webapp</directory>
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/**</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/**</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
以上是pom依赖,记录一下。