元素结合 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的响应式数据和事件绑定特性来完成。主要思路是利用v-show或v-if控制下拉菜单的显示与隐藏,并通过鼠标事件或点击事件触发状态变化。…

vue实现3d宇宙

vue实现3d宇宙

Vue实现3D宇宙效果 使用Three.js库 Three.js是一个强大的JavaScript 3D库,可以轻松集成到Vue项目中。安装Three.js依赖: npm install three…

vue调用接口实现退出

vue调用接口实现退出

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

vue实现星星

vue实现星星

实现星星评分的Vue组件 使用Vue实现星星评分功能可以通过组件化方式完成,以下是一个完整的实现方案: 模板部分 <template> <div class="star-ra…

vue实现点击

vue实现点击

实现点击事件的基本方法 在Vue中实现点击事件可以通过v-on指令或@简写方式绑定。以下是常见的点击事件绑定方法: <template> <button v-on:click…

vue实现递归

vue实现递归

Vue 实现递归组件的方法 在 Vue 中实现递归组件通常用于处理树形结构数据(如菜单、评论列表、文件目录等)。以下是具体实现方法: 定义递归组件 通过 name 选项让组件可以递归调用自身:…