vue如何使用element实现上传图片和修改图片功能

发布时间:2022-07-11 09:41:27 作者:iii
来源:亿速云 阅读:809

Vue如何使用Element实现上传图片和修改图片功能

在现代Web开发中,图片上传和修改功能是非常常见的需求。Vue.js流行的前端框架,结合Element UI组件库,可以非常方便地实现这些功能。本文将详细介绍如何使用Vue和Element UI实现图片上传和修改功能,并提供一个完整的示例。

1. 环境准备

在开始之前,确保你已经安装了Vue.js和Element UI。如果还没有安装,可以通过以下命令进行安装:

# 使用Vue CLI创建项目
vue create my-project

# 进入项目目录
cd my-project

# 安装Element UI
npm install element-ui --save

安装完成后,在main.js中引入Element UI:

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

Vue.use(ElementUI);

2. 图片上传功能

2.1 基本实现

Element UI提供了一个el-upload组件,可以方便地实现图片上传功能。以下是一个简单的图片上传示例:

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :limit="1"
      :file-list="fileList"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
    };
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
  },
};
</script>

2.2 上传前的校验

在实际应用中,我们通常需要对上传的图片进行一些校验,例如文件类型、文件大小等。可以通过before-upload钩子来实现:

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :limit="1"
      :file-list="fileList"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
    };
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },
  },
};
</script>

2.3 自定义上传行为

有时候我们需要自定义上传行为,例如使用axios进行上传。可以通过http-request属性来实现:

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :http-request="customUpload"
      :limit="1"
      :file-list="fileList"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
    };
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },
    customUpload(file) {
      const formData = new FormData();
      formData.append('file', file.file);

      axios.post('https://your-upload-url.com/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }).then(response => {
        this.fileList.push({
          name: file.file.name,
          url: response.data.url,
        });
      }).catch(error => {
        console.error('上传失败', error);
      });
    },
  },
};
</script>

3. 图片修改功能

3.1 基本实现

图片修改功能通常包括重新上传图片或对已上传的图片进行裁剪、旋转等操作。以下是一个简单的图片修改示例:

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :limit="1"
      :file-list="fileList"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
    <el-button type="primary" @click="handleEdit">修改图片</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
    };
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },
    handleEdit() {
      if (this.fileList.length > 0) {
        this.dialogImageUrl = this.fileList[0].url;
        this.dialogVisible = true;
      } else {
        this.$message.warning('请先上传图片');
      }
    },
  },
};
</script>

3.2 图片裁剪功能

为了实现图片裁剪功能,可以使用第三方库如cropperjs。以下是一个简单的图片裁剪示例:

<template>
  <div>
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :limit="1"
      :file-list="fileList"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img ref="image" :src="dialogImageUrl" alt="" />
      <el-button type="primary" @click="cropImage">裁剪图片</el-button>
    </el-dialog>
  </div>
</template>

<script>
import Cropper from 'cropperjs';
import 'cropperjs/dist/cropper.css';

export default {
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      cropper: null,
    };
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.cropper = new Cropper(this.$refs.image, {
          aspectRatio: 1,
          viewMode: 1,
        });
      });
    },
    handleSuccess(response, file, fileList) {
      this.fileList = fileList;
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },
    cropImage() {
      const croppedCanvas = this.cropper.getCroppedCanvas();
      croppedCanvas.toBlob(blob => {
        const file = new File([blob], 'cropped-image.png', { type: 'image/png' });
        this.fileList = [{ name: file.name, url: URL.createObjectURL(file) }];
        this.dialogVisible = false;
      });
    },
  },
};
</script>

4. 总结

通过Vue和Element UI,我们可以非常方便地实现图片上传和修改功能。本文详细介绍了如何使用el-upload组件实现图片上传、上传前的校验、自定义上传行为,以及如何实现图片修改和裁剪功能。希望本文能帮助你在实际项目中更好地实现这些功能。

如果你有任何问题或建议,欢迎在评论区留言讨论。

推荐阅读:
  1. Vue+Element-UI实现上传图片并压缩
  2. Django如何实现上传图片功能

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

element vue

上一篇:vue如何导入处理Excel表格

下一篇:VUE如何解决跨域问题

相关阅读

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

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