欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 新车 > el-upload如何自定展示上传的文件

el-upload如何自定展示上传的文件

2025/2/22 16:43:13 来源:https://blog.csdn.net/qq_29579625/article/details/142343930  浏览:    关键词:el-upload如何自定展示上传的文件

 Element UI 中,el-upload 组件支持通过插槽(slot)来自定义文件列表的展示方式。这通常是通过 file-list 插槽来实现的。下面是一个使用 el-upload 组件并通过 file-list 插槽来自定义文件列表展示的完整示例代码。

在这个示例中,我将展示如何自定义每个文件的显示方式,包括文件名、文件大小、上传进度和删除操作。

<template>  <div>  <el-upload  class="upload-demo"  action="你的文件上传接口URL"  :on-preview="handlePreview"  :on-remove="handleRemove"  :file-list="fileList"  :auto-upload="true" <!-- 设置为true以自动上传文件 -->  :on-change="handleChange"  :on-progress="handleProgress" <!-- 监听上传进度 -->  multiple  >  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>  <!-- 自定义文件列表 -->  <div slot="file" slot-scope="{file}"><div class="file-name">{{ file.name }}</div>  <div class="file-size">{{ formatFileSize(file.size) }}</div>  <div v-if="file.percentage" class="file-progress">{{ file.percentage }}%</div>  <el-button  size="mini"  type="danger"  @click="handleRemove(file.name, fileList, index)"  >删除</el-button>  </div>  </el-upload>  </div>  
</template>  <script>  
export default {  data() {  return {  fileList: []  };  },  methods: {  handlePreview(file) {  console.log('preview', file);  },  handleRemove(fileName, fileList, index) {  const removedFile = fileList.find(f => f.name === fileName);  if (removedFile) {  // 停止上传(如果支持的话)  // 注意:Element UI 的 el-upload 组件没有直接提供停止上传的API  // 但你可以通过其他方式(如取消XHR请求)来实现  // 然后从fileList中移除文件  this.$set(fileList, index, null);  fileList.splice(index, 1);  }  },  handleChange(file, fileList) {  // 这里通常不需要手动修改fileList,除非你有特殊的处理逻辑  },  handleProgress(event, file, fileList) {  // 更新文件的上传进度  for (let i = 0; i < fileList.length; i++) {  if (fileList[i].raw === file.raw) {  fileList[i].percentage = event.percent; // 假设event.percent是上传进度百分比  break;  }  }  },  formatFileSize(size) {  if (size / 1024 > 1024) {  return (size / 1024 / 1024).toFixed(2) + ' MB';  } else {  return (size / 1024).toFixed(2) + ' KB';  }  }  }  
};  
</script>  <style>  
.upload-file-list .upload-file-item {  margin-top: 10px;  display: flex;  justify-content: space-between;  align-items: center;  
}  .upload-file-list .file-name,  
.upload-file-list .file-size {  margin-right: 10px;  
}  
</style>

请注意,在上面的代码中,我通过 handleRemove 方法手动从 fileList 中删除了文件。然而,在 Element UI 的正常用法中,如果你使用了 :file-list="fileList" 绑定,并且你的上传逻辑(包括删除)都通过 Element UI 的事件(如 @remove)来处理,那么你可能不需要在 handleRemove 方法中手动操作 fileList。但在某些情况下,你可能需要更细粒度的控制,这时就需要手动操作了。

此外,action 属性应该指向你的实际文件上传接口。我在示例中使用了 https://jsonplaceholder.typicode.com/posts/ 作为示例,这只是一个返回JSON数据的占位符API,并不支持文件上传。你需要将其替换为你的实际文件上传接口。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词