Vue-12-图片上传预览

50 阅读2分钟

一、概述

图片上传预览是一个比较常用的功能,经常在各种项目中会用到。
本章节知识点主要如下:

  • FileReader的使用
  • 图片如何实现上传预览
  • 按钮样式的优化 借助阿里的AI 通义灵码完成了。

二、实现

仍然是采用Vue组件的方式进行开发,组件代码如下:

<template>
  <div id="app">
    <h1>图片预览</h1>
    <input type="file" ref="fileInput" @change="handleFileChange" accept="image/*" multiple class="file-input">
    <button @click="selectFiles" class="custom-file-button">选择文件</button>
    <div v-if="previewUrl">
      <img :src="previewUrl" alt="预览图片" style="max-width: 300px;">
    </div>
    <div v-if="previewUrls.length > 0">
      <h2>已上传图片预览</h2>
      <div v-for="(url, index) in previewUrls" :key="index">
        <img :src="url" alt="预览图片" style="max-width: 300px;">
        <button @click="removeImage(index)" class="remove-button">删除</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      previewUrl: null,
      previewUrls: []
    };
  },
  methods: {
    /**
     * 处理文件选择事件
     * 此函数用于处理文件选择输入的变化,筛选出所有图像文件并预览它们
     * @param {Object} event - 事件对象,包含选择的文件信息
     */
    handleFileChange(event) {
      // 获取选择的文件列表
      const files = event.target.files;
      // 遍历所有选择的文件
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        // 检查文件是否为图像类型
        if (!file.type.startsWith('image/')) {
          continue;
        }
        // 创建FileReader对象以读取文件内容
        const reader = new FileReader();
        // 文件读取完成后的回调函数,将图像数据URL添加到预览URL列表
        reader.onload = (e) => {
          this.previewUrls.push(e.target.result);
        };
        // 使用FileReader读取文件并将其转换为DataURL格式
        reader.readAsDataURL(file);
      }
    },
    selectFiles() {
      this.$refs.fileInput.click(); // 触发文件选择框
    },
    /**
     * 移除指定索引的预览图片
     * 
     * 此方法用于从预览图片列表中移除特定的图片。在用户界面中,当用户决定不再使用某张图片时,
     * 可以调用此方法将该图片从预览列表中移除,从而更新用户界面并释放不再需要的图片资源。
     * 
     * @param {number} index - 要移除的图片在预览列表中的索引位置
     */
    removeImage(index) {
      this.previewUrls.splice(index, 1);
    }
  }
};
</script>

<style scoped>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.file-input {
  display: none;
  /* 隐藏默认的文件输入框 */
}

/* 自定义文件选择按钮 */
.custom-file-button {
  background-color: #1890ff;
  /* 蓝色背景 */
  color: white;
  /* 白色文字 */
  border: none;
  padding: 10px 20px;
  cursor: pointer;
  font-size: 16px;
  border-radius: 4px;
  outline: none;
}

.custom-file-button:hover {
  background-color: #1377db;
  /* 鼠标悬停时更深的蓝色 */
}

.remove-button {
  background-color: #ff4d4f;
  /* 红色背景 */
  color: white;
  /* 白色文字 */
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  font-size: 14px;
  border-radius: 4px;
  margin-left: 10px;
}

.remove-button:hover {
  background-color: #c82c2c;
  /* 鼠标悬停时更深的红色 */
}
</style>

实现效果:

image.png

三、总结

实现过程中,借助AI完成了样式的优化,对关键代码FileReader进行了注释。
隐藏了input按钮,通过button来触发文件上传。
AI大大提升了编程学习的效率。