基于vant3组件的文件上传

基于vant3组件的文件上传

  1. 前台代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<van-form @submit="onSubmit" class="form1">
<van-cell-group inset>
<van-popup v-model:show="showPicker" position="bottom">
<van-picker
:columns="columns"
@confirm="onConfirm"
@cancel="showPicker = false"
:columns-field-names="customFieldName"
/>
</van-popup>
<van-field name="uploader" label="图片">
<template #input>
<van-uploader v-model="fileList"/>
</template>
</van-field>
</van-cell-group>

<script>
const onSubmit = (values) => {

let form = document.querySelector(".form1");
let formData = new FormData(form);
let upload = fileList.value[0]
if (upload == undefined) {
Toast("您未上传图片,请上传图片!")
return
}
formData.append("file", upload.file);
addArticle(formData).then(res => {
if (res == "1") {
Toast("添加成功!")
router.push("/mine")
} else {
Toast("添加失败,请重写头条信息!")
}
})
};
</script>

image

2.后台逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@PostMapping("/add")
int add(Article article, MultipartFile file) {
if (file == null || file.isEmpty()) {
return 0;
}
//将上传的文件重命名
String filename = file.getOriginalFilename();
String newName = UUID.randomUUID().toString().replaceAll("-", "") + filename.substring(filename.lastIndexOf("."));
//文件上传到uploadPath
try {
file.transferTo(new File(this.uploadPath + newName));
} catch (IOException e) {
e.printStackTrace();
}
article.setPictures(newName);
article.setType(1);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
article.setTime(dateFormat.format(new Date()));
boolean result = articleService.save(article);
if (result) {
return 1;
}
return 0;
}

基于vant3组件的文件上传
https://yunfreehh.github.io/2023/03/20/基于vant3组件的文件上传/
作者
yunfree
发布于
2023年3月20日
许可协议