当前位置:首页 > VUE

vue实现图片上传源码

2026-01-23 05:49:09VUE

Vue 图片上传实现源码

以下是一个基于 Vue 的图片上传组件实现,包含前端代码和关键逻辑说明。示例使用 axios 发送请求,并支持预览、限制文件类型和大小等功能。

基础模板结构

<template>
  <div class="upload-container">
    <input 
      type="file" 
      accept="image/*" 
      @change="handleFileChange" 
      ref="fileInput"
    />
    <button @click="triggerUpload">选择图片</button>

    <!-- 图片预览 -->
    <div v-if="previewUrl" class="preview">
      <img :src="previewUrl" alt="预览" />
      <button @click="removeImage">删除</button>
    </div>

    <!-- 上传按钮 -->
    <button 
      @click="uploadImage" 
      :disabled="!selectedFile"
    >上传</button>

    <!-- 进度条 -->
    <div v-if="uploadProgress > 0" class="progress">
      <div :style="{ width: uploadProgress + '%' }"></div>
    </div>
  </div>
</template>

脚本逻辑

<script>
import axios from 'axios';

export default {
  data() {
    return {
      selectedFile: null,
      previewUrl: '',
      uploadProgress: 0
    };
  },
  methods: {
    triggerUpload() {
      this.$refs.fileInput.click();
    },

    handleFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;

      // 校验文件类型和大小(示例限制2MB)
      const validTypes = ['image/jpeg', 'image/png', 'image/gif'];
      const maxSize = 2 * 1024 * 1024; // 2MB

      if (!validTypes.includes(file.type)) {
        alert('仅支持JPEG/PNG/GIF格式');
        return;
      }

      if (file.size > maxSize) {
        alert('文件大小不能超过2MB');
        return;
      }

      this.selectedFile = file;
      this.previewUrl = URL.createObjectURL(file);
    },

    removeImage() {
      this.selectedFile = null;
      this.previewUrl = '';
      this.$refs.fileInput.value = '';
    },

    async uploadImage() {
      if (!this.selectedFile) return;

      const formData = new FormData();
      formData.append('image', this.selectedFile);

      try {
        const res = await axios.post('/api/upload', formData, {
          onUploadProgress: (progressEvent) => {
            this.uploadProgress = Math.round(
              (progressEvent.loaded / progressEvent.total) * 100
            );
          }
        });

        alert('上传成功');
        this.$emit('uploaded', res.data.url); // 触发成功回调
        this.removeImage();
      } catch (error) {
        alert('上传失败: ' + error.message);
      } finally {
        this.uploadProgress = 0;
      }
    }
  }
};
</script>

样式示例

<style scoped>
.upload-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-width: 500px;
}

input[type="file"] {
  display: none;
}

.preview img {
  max-width: 100%;
  max-height: 200px;
}

.progress {
  height: 6px;
  background: #eee;
}

.progress div {
  height: 100%;
  background: #42b983;
  transition: width 0.3s;
}
</style>

关键功能说明

文件选择与预览
通过隐藏的 <input type="file"> 触发文件选择,使用 URL.createObjectURL 生成预览图的临时URL。

文件校验
handleFileChange 方法中对文件类型和大小进行校验,避免无效上传。

上传进度
通过 axiosonUploadProgress 回调实现实时进度显示,进度条通过CSS动态宽度呈现。

vue实现图片上传源码

后端对接
示例中上传接口为 /api/upload,实际需替换为真实接口地址。后端需接收 multipart/form-data 格式数据。

扩展建议

  1. 多图上传
    修改 inputmultiple 属性并调整逻辑为数组存储:

    vue实现图片上传源码

    <input type="file" multiple @change="handleFilesChange" />
  2. 拖拽上传
    添加拖拽区域事件监听:

    @dragover.prevent
    @drop.prevent="handleDrop"
  3. 图片裁剪
    集成第三方库如 cropperjs 实现前端裁剪功能。

  4. 云存储直传
    如需上传至阿里云OSS或七牛云等,可使用各平台提供的SDK实现签名直传。

分享给朋友:

相关文章

php实现图片上传

php实现图片上传

实现图片上传的基本步骤 创建HTML表单用于文件上传,表单需设置enctype="multipart/form-data"属性,确保文件数据正确传输。 <form action="upload…

vue实现登录源码

vue实现登录源码

以下是一个基于 Vue.js 的登录功能实现示例,包含前端代码和关键逻辑说明: 登录页面组件 <template> <div class="login-container"&…

h5移动端实现图片上传

h5移动端实现图片上传

移动端H5图片上传实现方法 使用input元素 在H5页面中添加一个input元素,设置type为file,并添加accept属性限制文件类型为图片: <input type="file" a…

js图片上传实现

js图片上传实现

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API实现基础图片上传功能。HTML部分需要设置accept="image/…

如何阅读java源码

如何阅读java源码

阅读Java源码的方法 选择合适的源码项目 初学者建议从JDK核心类库(如java.lang、java.util)或知名开源项目(如Spring、Guava)入手。选择文档完善、社区活跃的项目能降低理…

php实现图片上传预览

php实现图片上传预览

图片上传预览的实现方法 在PHP中实现图片上传预览功能,通常需要结合前端JavaScript和后端PHP代码。以下是具体的实现步骤: 前端HTML和JavaScript部分 创建包含文件输入和…