Solve the problem of @change not triggering twice when uploading the same file/picture when input type="file"

Solve the problem of @change not triggering twice when uploading the same file/picture when input type="file"

1. Application scenarios

Application scenario: Select the file to be imported in this computer. The file type is arbitrary. After double-clicking the file, you need to preview it in the list. After the preview is correct, click to save the imported data.
Insert image description here
Insert image description here

2. Code implementation

<template>
  <div>
    <div class="file-input-container">
      <el-button type="primary"> 导入 </el-button>
      <input type="file" class="file-input" @change="handleFileImport" />
    </div>
    <el-button
      type="primary"
      style="margin-right: 12px"
      @click="saveImportData()"
    >
      保存导入数据
    </el-button>
  </div>
</template>

<script lang='ts'>
import {
    
     defineComponent, reactive, ref } from 'vue';
import {
    
     List, previewImported } from '@/services/list';
interface ViewState {
    
    
  list: List[];
  selectedFile: File | null;
}
export default {
    
    
  name: '',
  setup() {
    
    
    const state = reactive<ViewState>({
    
    
      selectedFile: null,
      list: [],
    });

    function saveImportData() {
    
    
      // 保存请求接口逻辑
    }
    return {
    
    
      state,
      saveImportData,
    };
  },

  methods: {
    
    
    handleFileImport(evt) {
    
    
      let [file] = evt.target.files;
      this.selectedFile = file;
      const data = new FormData();
      data.append('file', file);
      // 导入后的数据预览
      previewImported(data)
        .then((response) => {
    
    
          // 使用数组的格式 接收response这里是因为返回的response为数组对象格式:[{}],list和response为一样的格式类型 可省略
          //const order: [] = response;
          this.list = order;
        })
        .finally(() => {
    
    
          // 解决上传同一文件时无法请求接口:上传完上一个文件后 清空上一个文件的内容 用以保证下一次上传时获取的是一个新的文件而不是一个重复的文件
          evt.target.value = '';
        });
    },
  },
};
</script>
<style scoped>
</style>

Guess you like

Origin blog.csdn.net/m0_50298323/article/details/134307254