当前位置:首页 > VUE

vue 实现图片上传demo

2026-02-24 16:08:51VUE

安装依赖

确保项目中已安装axios用于文件上传请求,若未安装可通过以下命令安装:

npm install axios

前端组件实现

创建图片上传组件ImageUpload.vue,包含文件选择、预览和上传功能:

<template>
  <div>
    <input type="file" @change="handleFileChange" accept="image/*" />
    <img v-if="previewUrl" :src="previewUrl" width="200" />
    <button @click="uploadImage" :disabled="!file">Upload</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
      previewUrl: ''
    };
  },
  methods: {
    handleFileChange(event) {
      this.file = event.target.files[0];
      this.previewUrl = URL.createObjectURL(this.file);
    },
    async uploadImage() {
      const formData = new FormData();
      formData.append('image', this.file);

      try {
        const response = await axios.post('/api/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        console.log('Upload success:', response.data);
      } catch (error) {
        console.error('Upload failed:', error);
      }
    }
  }
};
</script>

后端接口示例(Node.js)

创建简单的Express服务端接口处理上传:

vue 实现图片上传demo

const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({ dest: 'uploads/' });

app.post('/api/upload', upload.single('image'), (req, res) => {
  console.log('File received:', req.file);
  res.json({ message: 'File uploaded successfully' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

跨域处理

若前后端分离开发,需配置代理或CORS。在vue.config.js中添加:

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true
      }
    }
  }
};

文件大小限制

可在前端和后端分别设置限制: 前端验证文件大小:

vue 实现图片上传demo

handleFileChange(event) {
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (event.target.files[0].size > maxSize) {
    alert('File too large');
    return;
  }
  // ...其余代码
}

后端限制(使用multer):

const upload = multer({
  dest: 'uploads/',
  limits: { fileSize: 5 * 1024 * 1024 }
});

进度显示

通过axios的onUploadProgress实现上传进度条:

uploadImage() {
  const config = {
    headers: { 'Content-Type': 'multipart/form-data' },
    onUploadProgress: progressEvent => {
      const percent = Math.round(
        (progressEvent.loaded * 100) / progressEvent.total
      );
      console.log(`${percent}% uploaded`);
    }
  };
  axios.post('/api/upload', formData, config);
}

标签: 图片上传vue
分享给朋友:

相关文章

vue实现购物按钮

vue实现购物按钮

Vue 购物按钮实现方法 基础按钮实现 使用 Vue 的模板语法创建基础按钮组件,绑定点击事件处理购物逻辑: <template> <button @click="addToC…

vue实现打字机

vue实现打字机

Vue实现打字机效果 在Vue中实现打字机效果可以通过动态更新文本内容并添加延迟来实现。以下是几种常见的实现方法: 使用setInterval实现 <template> <…

eventbus vue实现

eventbus vue实现

EventBus 实现原理 EventBus 是一种发布/订阅模式,用于 Vue 组件间的通信。核心是通过一个中央事件总线管理事件监听和触发。 创建 EventBus 在 Vue 项目中创建一个独立…

vue实现引导

vue实现引导

Vue 实现引导功能的方法 使用第三方库 推荐使用 driver.js 或 intro.js 这类专门为 Vue 设计的引导库。这些库提供了完整的 API 和样式,能够快速实现引导功能。 安装 dr…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

vue实现radio

vue实现radio

Vue 实现 Radio 按钮 在 Vue 中实现 Radio 按钮可以通过 v-model 进行数据绑定,结合 input 元素的 type="radio" 属性。以下是一个基本示例: <t…