Vue通过原始文件选择框实现文件上传(支持批量)

页面效果图:

代码模板:

 1 <v-block>
 2   <input
 3     type="file"
 4     name="file"
 5     class="el-upload__input"
 6     @change="selectFileEvent(fileNameList)"
 7     multiple
 8     ref="file2"
 9   />
10   <el-form>
11     <el-form-item label="选择文件">
12       <el-input
13         type="text"
14         v-model="fileNameList"
15         style="width: 50%"
16         disabled
17       ></el-input>
18       <el-button @click="fileSelect">...</el-button>
19     </el-form-item>
20   </el-form>
21 </v-block>

一、给选择文件按钮绑定单击事件——去触发type="file"的input标签

1 // 加号选择文件
2 fileSelect(index) {
3    this.$refs.file2.click(index);
4 }

二、给文件选择标签绑定change事件

 1 // 加号选定文件
 2 selectFileEvent(fileNameList) {
 3   // 清空文件名列表和文件
 4   var fileNameList = "";
 5   let formDate = this.$refs.file2.files;
 6   for (let i = 0; i < formDate.length; i++) {
 7     if (formDate[i].name != null || formDate[i].name != "") {
 8       if (formDate[i].name.length > 20) {
 9         let name = formDate[i].name.split(".");
10         // console.log(name,'name')
11         fileNameList =
12           fileNameList +
13           `${name[0].substr(0, 16)}... .${name[name.length - 1]}` +
14           ";";
15       } else {
16         fileNameList = fileNameList + formDate[i].name + ";";
17       }
18     }
19   }
20   this.fileNameList = fileNameList;
21   this.fileList = formDate;
22 },

三、支持批量属性

multiple

四、后端接口定义

1 public ResponseEntity<?> fileUpload(@RequestPart(required = false, value = "files") MultipartFile[] files) {
2     return ResponseEntity.ok(true);
3 }

 

posted @ 2022-03-25 13:26  没有你哪有我  阅读(780)  评论(1编辑  收藏  举报