VUE+element-ui文件上传的代码怎么写

发布时间:2022-03-04 10:19:24 作者:iii
来源:亿速云 阅读:238

VUE+element-ui文件上传的代码怎么写

在现代Web开发中,文件上传是一个常见的需求。无论是上传图片、文档还是其他类型的文件,开发者都需要一个可靠且易于使用的解决方案。Vue.js流行的前端框架,结合Element UI组件库,可以轻松实现文件上传功能。本文将详细介绍如何使用Vue.js和Element UI实现文件上传功能,并提供完整的代码示例。

1. 环境准备

在开始编写代码之前,我们需要确保开发环境已经准备好。以下是所需的工具和库:

1.1 安装Vue CLI

如果你还没有安装Vue CLI,可以通过以下命令进行安装:

npm install -g @vue/cli

1.2 创建Vue项目

使用Vue CLI创建一个新的Vue项目:

vue create vue-file-upload

在创建项目时,选择默认配置或手动选择需要的特性。

1.3 安装Element UI

进入项目目录并安装Element UI:

cd vue-file-upload
npm install element-ui --save

1.4 引入Element UI

src/main.js中引入Element UI:

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';

Vue.use(ElementUI);

new Vue({
  render: h => h(App),
}).$mount('#app');

2. 文件上传组件的基本使用

Element UI提供了一个el-upload组件,用于实现文件上传功能。我们可以通过简单的配置来实现文件上传。

2.1 基本用法

src/components/FileUpload.vue中创建一个文件上传组件:

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :file-list="fileList"
      list-type="picture"
    >
      <el-button type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
    };
  },
  methods: {
    handlePreview(file) {
      console.log('预览文件:', file);
    },
    handleRemove(file, fileList) {
      console.log('移除文件:', file);
      this.fileList = fileList;
    },
    beforeUpload(file) {
      console.log('上传前:', file);
      return true;
    },
    handleSuccess(response, file, fileList) {
      console.log('上传成功:', response);
      this.fileList = fileList;
    },
    handleError(err, file, fileList) {
      console.error('上传失败:', err);
      this.fileList = fileList;
    },
  },
};
</script>

<style scoped>
/* 样式可以根据需要进行调整 */
</style>

2.2 代码解析

2.3 运行项目

在项目根目录下运行以下命令启动开发服务器:

npm run serve

打开浏览器访问http://localhost:8080,你将看到一个文件上传组件。点击“点击上传”按钮,选择文件后,文件将被上传到指定的服务器地址。

3. 文件上传的高级配置

在实际开发中,我们可能需要对文件上传进行更多的控制,例如限制文件类型、大小、上传进度等。Element UI的el-upload组件提供了丰富的配置选项,可以满足这些需求。

3.1 限制文件类型和大小

我们可以通过before-upload钩子函数来限制上传文件的类型和大小。

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :file-list="fileList"
      list-type="picture"
    >
      <el-button type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
    };
  },
  methods: {
    handlePreview(file) {
      console.log('预览文件:', file);
    },
    handleRemove(file, fileList) {
      console.log('移除文件:', file);
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!');
      }
      return isJPG && isLt500K;
    },
    handleSuccess(response, file, fileList) {
      console.log('上传成功:', response);
      this.fileList = fileList;
    },
    handleError(err, file, fileList) {
      console.error('上传失败:', err);
      this.fileList = fileList;
    },
  },
};
</script>

<style scoped>
/* 样式可以根据需要进行调整 */
</style>

3.2 显示上传进度

Element UI的el-upload组件默认不显示上传进度,但我们可以通过on-progress钩子函数来实现进度显示。

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      :file-list="fileList"
      list-type="picture"
    >
      <el-button type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
    <el-progress :percentage="uploadPercentage" v-if="uploadPercentage > 0"></el-progress>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
      uploadPercentage: 0,
    };
  },
  methods: {
    handlePreview(file) {
      console.log('预览文件:', file);
    },
    handleRemove(file, fileList) {
      console.log('移除文件:', file);
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!');
      }
      return isJPG && isLt500K;
    },
    handleSuccess(response, file, fileList) {
      console.log('上传成功:', response);
      this.fileList = fileList;
      this.uploadPercentage = 0;
    },
    handleError(err, file, fileList) {
      console.error('上传失败:', err);
      this.fileList = fileList;
      this.uploadPercentage = 0;
    },
    handleProgress(event, file, fileList) {
      this.uploadPercentage = parseInt(event.percent);
    },
  },
};
</script>

<style scoped>
/* 样式可以根据需要进行调整 */
</style>

3.3 自定义上传请求

在某些情况下,我们可能需要自定义上传请求,例如添加请求头、处理跨域问题等。Element UI的el-upload组件支持通过http-request属性来自定义上传请求。

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      :file-list="fileList"
      list-type="picture"
      :http-request="customUpload"
    >
      <el-button type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
    <el-progress :percentage="uploadPercentage" v-if="uploadPercentage > 0"></el-progress>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      fileList: [],
      uploadPercentage: 0,
    };
  },
  methods: {
    handlePreview(file) {
      console.log('预览文件:', file);
    },
    handleRemove(file, fileList) {
      console.log('移除文件:', file);
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!');
      }
      return isJPG && isLt500K;
    },
    handleSuccess(response, file, fileList) {
      console.log('上传成功:', response);
      this.fileList = fileList;
      this.uploadPercentage = 0;
    },
    handleError(err, file, fileList) {
      console.error('上传失败:', err);
      this.fileList = fileList;
      this.uploadPercentage = 0;
    },
    handleProgress(event, file, fileList) {
      this.uploadPercentage = parseInt(event.percent);
    },
    customUpload(file) {
      const formData = new FormData();
      formData.append('file', file.file);

      axios.post('https://jsonplaceholder.typicode.com/posts/', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        onUploadProgress: (progressEvent) => {
          const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          this.uploadPercentage = percentCompleted;
        },
      })
        .then((response) => {
          this.handleSuccess(response, file, this.fileList);
        })
        .catch((error) => {
          this.handleError(error, file, this.fileList);
        });
    },
  },
};
</script>

<style scoped>
/* 样式可以根据需要进行调整 */
</style>

3.4 多文件上传

Element UI的el-upload组件默认支持多文件上传。我们可以通过multiple属性来启用多文件上传。

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      :file-list="fileList"
      list-type="picture"
      multiple
    >
      <el-button type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
    <el-progress :percentage="uploadPercentage" v-if="uploadPercentage > 0"></el-progress>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
      uploadPercentage: 0,
    };
  },
  methods: {
    handlePreview(file) {
      console.log('预览文件:', file);
    },
    handleRemove(file, fileList) {
      console.log('移除文件:', file);
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!');
      }
      return isJPG && isLt500K;
    },
    handleSuccess(response, file, fileList) {
      console.log('上传成功:', response);
      this.fileList = fileList;
      this.uploadPercentage = 0;
    },
    handleError(err, file, fileList) {
      console.error('上传失败:', err);
      this.fileList = fileList;
      this.uploadPercentage = 0;
    },
    handleProgress(event, file, fileList) {
      this.uploadPercentage = parseInt(event.percent);
    },
  },
};
</script>

<style scoped>
/* 样式可以根据需要进行调整 */
</style>

4. 文件上传的服务器端处理

在前端实现文件上传功能后,我们还需要在服务器端处理上传的文件。以下是一个简单的Node.js Express服务器示例,用于处理文件上传。

4.1 创建Express服务器

首先,创建一个新的Node.js项目并安装所需的依赖:

mkdir file-upload-server
cd file-upload-server
npm init -y
npm install express multer cors

4.2 编写服务器代码

在项目根目录下创建一个server.js文件,并编写以下代码:

const express = require('express');
const multer = require('multer');
const cors = require('cors');

const app = express();
const port = 3000;

app.use(cors());

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  },
});

const upload = multer({ storage });

app.post('/upload', upload.single('file'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded.');
  }
  res.send({ message: 'File uploaded successfully.', file: req.file });
});

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

4.3 运行服务器

在项目根目录下运行以下命令启动服务器:

node server.js

服务器启动后,将监听http://localhost:3000,并处理文件上传请求。

4.4 修改前端代码

将前端代码中的action属性修改为服务器的上传地址:

<template>
  <div>
    <el-upload
      action="http://localhost:3000/upload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :on-progress="handleProgress"
      :file-list="fileList"
      list-type="picture"
      multiple
    >
      <el-button type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
    </el-upload>
    <el-progress :percentage="uploadPercentage" v-if="uploadPercentage > 0"></el-progress>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
      uploadPercentage: 0,
    };
  },
  methods: {
    handlePreview(file) {
      console.log('预览文件:', file);
    },
    handleRemove(file, fileList) {
      console.log('移除文件:', file);
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!');
      }
      return isJPG && isLt500K;
    },
    handleSuccess(response, file, fileList) {
      console.log('上传成功:', response);
      this.fileList = fileList;
      this.uploadPercentage = 0;
    },
    handleError(err, file, fileList) {
      console.error('上传失败:', err);
      this.fileList = fileList;
      this.uploadPercentage = 0;
    },
    handleProgress(event, file, fileList) {
      this.uploadPercentage = parseInt(event.percent);
    },
  },
};
</script>

<style scoped>
/* 样式可以根据需要进行调整 */
</style>

5. 总结

通过本文的介绍,我们学习了

推荐阅读:
  1. php文件上传代码如何写
  2. vue+Element-ui实现分页效果实例代码详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue element

上一篇:如何解决SpringBoot测试时卡在Resolving Maven dependencies的问题

下一篇:Vue如何打包生成dist文件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》