元素结合 Vue 的 v-on:change 事件监听文件选择。在方法中通过 Form…">
当前位置:首页 > VUE

vue 实现上传文件

2026-01-19 15:15:23VUE

使用 Vue 实现文件上传

基础文件上传

通过 HTML 的 <input type="file"> 元素结合 Vue 的 v-on:change 事件监听文件选择。在方法中通过 FormData 对象处理文件并发送到服务器。

<template>
  <div>
    <input type="file" @change="handleFileUpload" />
    <button @click="uploadFile">上传</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      file: null
    };
  },
  methods: {
    handleFileUpload(event) {
      this.file = event.target.files[0];
    },
    uploadFile() {
      if (!this.file) return;

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

      axios.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        console.log('上传成功', response.data);
      }).catch(error => {
        console.error('上传失败', error);
      });
    }
  }
};
</script>

多文件上传

修改 handleFileUpload 方法以支持多文件选择,并通过循环将多个文件添加到 FormData 中。

handleFileUpload(event) {
  this.files = event.target.files; // 改为数组存储
},
uploadFiles() {
  const formData = new FormData();
  Array.from(this.files).forEach(file => {
    formData.append('files[]', file);
  });

  axios.post('/upload-multiple', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  });
}

文件预览

在文件选择后,通过 FileReader 对象生成预览(如图片缩略图)。

handleFileUpload(event) {
  const file = event.target.files[0];
  if (!file.type.match('image.*')) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    this.previewUrl = e.target.result;
  };
  reader.readAsDataURL(file);
}

进度条显示

利用 Axios 的 onUploadProgress 回调实现上传进度监控。

vue 实现上传文件

axios.post('/upload', formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
  onUploadProgress: progressEvent => {
    const percent = Math.round(
      (progressEvent.loaded * 100) / progressEvent.total
    );
    this.uploadProgress = percent;
  }
})

拖拽上传

通过 @dragover.prevent@drop.prevent 实现拖拽区域,在 drop 事件中获取文件。

<div 
  @dragover.prevent
  @drop.prevent="handleDrop"
  class="drop-zone"
>
  拖拽文件到此处
</div>

<script>
methods: {
  handleDrop(event) {
    this.file = event.dataTransfer.files[0];
  }
}
</script>

文件验证

在上传前对文件大小和类型进行校验。

vue 实现上传文件

validateFile(file) {
  const validTypes = ['image/jpeg', 'image/png'];
  const maxSize = 2 * 1024 * 1024; // 2MB

  if (!validTypes.includes(file.type)) {
    alert('仅支持JPEG/PNG格式');
    return false;
  }
  if (file.size > maxSize) {
    alert('文件大小超过限制');
    return false;
  }
  return true;
}

组件化封装

将上传逻辑封装为可复用的组件,通过 props 接收配置参数(如上传地址、文件类型限制等)。

props: {
  endpoint: {
    type: String,
    required: true
  },
  allowedTypes: {
    type: Array,
    default: () => ['image/*']
  }
}

服务器响应处理

根据服务器返回的状态码或消息显示成功/错误提示。

axios.post('/upload', formData)
  .then(response => {
    if (response.data.success) {
      this.$toast.success('上传成功');
    } else {
      this.$toast.error(response.data.message);
    }
  })

取消上传

通过 Axios 的 CancelToken 实现上传取消功能。

const source = axios.CancelToken.source();
axios.post('/upload', formData, {
  cancelToken: source.token
});

// 取消上传
cancelUpload() {
  source.cancel('用户取消上传');
}

标签: 上传文件vue
分享给朋友:

相关文章

vue 路由实现

vue 路由实现

Vue 路由实现方法 安装 Vue Router 使用 npm 或 yarn 安装 Vue Router 依赖包: npm install vue-router # 或 yarn add vue-r…

vue实现列表显示

vue实现列表显示

Vue 实现列表显示的方法 在 Vue 中实现列表显示通常使用 v-for 指令,结合数组或对象数据渲染动态列表。以下是几种常见的实现方式。 基本列表渲染 通过 v-for 指令遍历数组,动态生成列…

vue路由实现内部切换

vue路由实现内部切换

Vue 路由实现内部切换的方法 Vue Router 是 Vue.js 官方的路由管理器,用于实现单页应用(SPA)的页面切换。以下是几种常见的内部路由切换方式: 使用 <router-lin…

vue中如何实现循环

vue中如何实现循环

在 Vue 中实现循环 Vue 提供了 v-for 指令用于实现循环渲染列表数据。v-for 可以遍历数组、对象或数字范围,生成动态的 DOM 元素。 遍历数组 使用 v-for 遍历数组时,语法为…

vue穿梭框组件实现

vue穿梭框组件实现

实现基础穿梭框组件 在Vue中实现穿梭框组件,可以使用<el-transfer>(Element UI)或手动实现。以下是手动实现的核心逻辑: <template> &…

vue调用接口实现退出

vue调用接口实现退出

实现Vue退出功能的步骤 在Vue中调用接口实现退出功能通常需要与后端API交互,以下是实现方法: 前端实现 创建退出方法,调用后端API接口: methods: { logout() {…