一、编写前端上传文件代码
<html>
<head>
<title>file upload</title>
</head>
<body>
<form action="file" method="post" enctype="multipart/form-data">
<h1>文件上传</h1>
<input type="file" name="file">
<input type="submit" value="上传">
</form>
</body>
</html>
二、导入jar包(我自己在使用导入maven时用不了,手动导入jar包才可以)
jave.jar 是用于获取文件相关信息的jar包
提取码:dvvv
三、导入文件上传依赖
<!--导入filupload和io坐标-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
四、spring-mvc.xml配置文件上传解析器
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!--最大文件大小-->
<property name="maxUploadSize" value="500000"/>
</bean>
五、编写主代码
@RequestMapping(value = "/file",method = RequestMethod.POST)
@ResponseBody
public coid add(MultipartFile file){
long longtime = chapterService.getTime(file,"D://");//调用获取时长代码
String time = swich_time(longtime);
System.out.println(time);
}
获取时长(单位:ms)
public long getTime(MultipartFile multiFile,String filePath){
try {
//根据传入的路径和MultipartFile对象,将视频保存到指定位置
//filePath为保存路径,multiFile.getOriginalFilename()为文件名
File file = new File(filePath+"\\"+multiFile.getOriginalFilename());
file.createNewFile();
//执行这个方法之后,MultipartFile对象就变成file对象了,就不能使用MultipartFile对象属性了
multiFile.transferTo(file);
//获取文件相关信息
Encoder encoder = new Encoder();
MultimediaInfo info = encoder.getInfo(file);
//获取视频时长
return info.getDuration();
} catch (IOException e) {
e.printStackTrace();
}catch (EncoderException e) {
e.printStackTrace();
}
return 0;
}
将毫秒转换成HH:mm:ss格式
public String swich_time(long time) {
//这里想要只保留分秒可以写成"mm:ss"
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
//这里很重要,如果不设置时区的话,输出结果就会是几点钟,而不是毫秒值对应的时分秒数量了。
formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
String hms = formatter.format(time);
return hms;
}
这样就可以获取视频的时长了,有用的话就点个赞吧!