1.controller 层代码
@RequestMapping(value = "uploadVidoe", method = RequestMethod.POST)
@ResponseBody
public Map<String,String> savaVideo(@RequestParam("file") MultipartFile file)
throws IllegalStateException {
Map<String,String> resultMap = new HashMap<>();
try{
//获取文件后缀
String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1)
.toLowerCase();
// 重构文件名称
String pikId = UUID.randomUUID().toString().replaceAll("-", "");
String newVidoeName = pikId + "." + fileExt;
//保存视频
File fileSave = new File(savePaths, newVidoeName);
file.transferTo(fileSave);
resultMap.put("resCode","1");
resultMap.put("webShowPath",webPaths + newVidoeName);
return resultMap;
}catch (Exception e){
e.printStackTrace();
resultMap.put("resCode","0");
return resultMap ;
}
}
前端代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<script th:src="@{/jquery-3.3.1.js}">
</script>
</head>
<body>
<span><input style="width: 75%; height: 100%;display: block" type="file" name="myfile" onchange="uploadVidoe(this)"/>
</span>
</body>
<script>
function uploadVidoe(vidoe) {
var fileObj = vidoe.files[0]; // 获取文件对象
if (fileObj != undefined) {
if (fileObj.name) {
console.log(fileObj.name)
} else {
alert("请选择文件");
}
var size = fileObj.size;
var type = fileObj.type;
//校验格式
if (type.indexOf('mp4') == -1) {
alert("请上传MP4格式")
return false;
}
//校验大小
if (size / 1024 / 2014 > 10) {
alert("请上传" + size + "之内的视频")
return false;
}
var form = new FormData(); // FormData 对象
form.append("file", fileObj);
$.ajax({
url: "uploadVidoe",
contentType: false,//false 传输对象
processData: false,
type: "POST",
data: form,
success: function (ret) {
if(ret.resCode != undefined){
if(ret.resCode == '1'){
alert("上传成功")
}
else if(ret.resCode == '0'){
alert("上传失败")
}
}
}
})
}
}
</script>
</html>
页面
上传的视频
git https://github.com/13030509/test.git
记录一下,希望给路过的朋友一点帮助