元素,并结合 FormData 对象将文件数据发送到后端。…">
当前位置:首页 > VUE

vue实现文件上传前后

2026-01-22 19:09:37VUE

Vue 文件上传前后端实现

前端实现(Vue)

在 Vue 中实现文件上传通常需要使用 <input type="file"> 元素,并结合 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]
    },
    async uploadFile() {
      if (!this.file) return

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

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

后端实现(Node.js Express)

后端接收文件需要使用中间件如 multer 来处理 multipart/form-data 格式的请求。

const express = require('express')
const multer = require('multer')
const path = require('path')

const app = express()

// 配置 multer 存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/')
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname))
  }
})

const upload = multer({ storage })

app.post('/api/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('没有文件被上传')
  }
  res.json({
    message: '文件上传成功',
    filename: req.file.filename,
    path: req.file.path
  })
})

app.listen(3000, () => {
  console.log('服务器运行在 http://localhost:3000')
})

文件上传进度显示

在 Vue 中可以使用 Axios 的 onUploadProgress 回调来显示上传进度。

methods: {
  async uploadFile() {
    if (!this.file) return

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

    try {
      const response = await axios.post('/api/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          console.log('上传进度:', percentCompleted + '%')
        }
      })
      console.log('上传成功:', response.data)
    } catch (error) {
      console.error('上传失败:', error)
    }
  }
}

文件类型和大小验证

在前端和后端都应该验证文件类型和大小以确保安全性。

vue实现文件上传前后

// 前端验证
handleFileUpload(event) {
  const file = event.target.files[0]
  const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf']
  const maxSize = 5 * 1024 * 1024 // 5MB

  if (!allowedTypes.includes(file.type)) {
    alert('不支持的文件类型')
    return
  }

  if (file.size > maxSize) {
    alert('文件大小超过限制')
    return
  }

  this.file = file
}
// 后端验证 (multer 配置)
const fileFilter = (req, file, cb) => {
  const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf']
  if (!allowedTypes.includes(file.mimetype)) {
    return cb(new Error('不支持的文件类型'), false)
  }
  cb(null, true)
}

const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
})

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

相关文章

vue实现滚动中断

vue实现滚动中断

Vue 实现滚动中断的方法 在 Vue 中实现滚动中断通常涉及监听滚动事件,并在特定条件下阻止默认行为或停止滚动。以下是几种常见方法: 监听滚动事件并阻止默认行为 通过 @scroll 或 @whe…

vue实现收起展开面板

vue实现收起展开面板

实现收起展开面板的方法 在Vue中实现收起展开面板功能可以通过多种方式完成,以下是几种常见的实现方法: 使用v-show或v-if控制显示隐藏 利用Vue的指令可以轻松实现面板的展开和收起:…

vue 实现

vue 实现

Vue 实现的基本步骤 安装 Vue.js 可以通过 npm 或 CDN 引入。使用 npm 安装适合大型项目,CDN 适合快速原型开发。 npm install vue 在 HTML 文件中引入…

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: <…

vue实现flvvideo

vue实现flvvideo

vue-flv-player 实现 FLV 视频播放 安装依赖包 npm install flv.js vue-flv-player 基础组件引入 <template> <v…

vue实现评分

vue实现评分

Vue 实现评分功能 使用组件库实现 安装 element-ui 或 ant-design-vue 这类 UI 库,它们已经内置了评分组件。 以 element-ui 为例: <te…