前端使用VUE
后端使用SpringBoot
前端
获取文件:
<el-upload
action=""
accept="video/*"
:on-change="onUploadChange"
:auto-upload="false"
:show-file-list="true"
>
<el-button slot="trigger" size="small" type="primary"
>选取</el-button
>
<el-button
style="margin-left: 10px"
size="small"
type="success"
@click="submitUpload"
>上传</el-button
>
</el-upload>
判断上传的文件是否符合预期:
onUploadChange(file) {
//保存上传的文件
this.file[0] = file;
const isIMAGE =
file.raw.type === "video/mp4" || file.raw.type === "audio/mp4";
const isLt1M = file.size / 1024 / 1024 / 1024 < 1;//大小要小于10MB
if (!isIMAGE) {
this.$message.error("上传文件只能是图片格式!");
return false;
}
if (!isLt1M) {
this.$message.error("上传文件大小不能超过 10MB!");
return false;
}
}
上传文件:
submitUpload(event) {
if (this.file.length == 0) {
this.$message({
type: "error",
message: "未选取文件",
});
return;
}
//event.preventDefault();
let formData = new FormData();
//数据
formData.append("file", this.file[0].raw);
formData.append("name", this.file[0].name);
//请求头
let config = {
headers: {
"Content-Type": "multipart/form-data",
},
};
//请求路径
let url = "http://localhost:5501/videoToAudio";
this.$axios.post(url, formData, config)
.then((res) => {
//上传成功后要进行的操作
})
.catch((res) => {
this.$message({
type: "error",
message: res
})
});
}
file内容一般是如下图格式:
后端
controller:
@RequestMapping(value = "请求名",method = RequestMethod.POST)
public void videoToAudio(@RequestParam("file") MultipartFile file,@RequestParam("name") String name){
if (file != null){
System.out.println("接收成功");
System.out.println("文件名:"+name);
}else{
System.out.println("接收失败");
}
}