当前位置: 代码网 > it编程>前端脚本>Vue.js > Vue如何实现文件预览和下载功能的前端上传组件

Vue如何实现文件预览和下载功能的前端上传组件

2024年10月28日 Vue.js 我要评论
前言在前端开发中,文件上传和预览是常见的功能需求之一。本文将介绍如何利用 vue.js 结合 element ui 的上传组件(el-upload)实现文件上传,并根据文件类型进行预览或下载的功能。1

前言

在前端开发中,文件上传和预览是常见的功能需求之一。本文将介绍如何利用 vue.js 结合 element ui 的上传组件(el-upload)实现文件上传,并根据文件类型进行预览或下载的功能。

1.准备工作

首先,确保你的项目中已经引入了 vue.js 和 element ui。在这个示例中,我们使用了 el-upload 组件来管理文件上传。

1.1 创建 vue 组件

在 vue 组件中,我们需要实现以下功能:

  • 文件上传功能
  • 文件预览功能(针对图片类型)
  • 文件下载功能(对于其他类型的文件)
<template>
  <div>
    <el-upload
      v-model:file-list="filelist"
      action="你的上传地址"
      :on-success="handlefilesuccess"
      :on-remove="handlefileremove"
      :on-error="handlefileerror"
      :limit="10"
      :data="fileformdata"
      name="files"
      :on-preview="openfile"
    >
      <el-button type="primary">点击上传</el-button>
    </el-upload>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      filelist: [], // 上传文件列表
      fileformdata: {}, // 额外的上传参数,如果需要的话
      imageextensions: ["jpg", "jpeg", "png", "gif", "bmp"], // 图片格式后缀
    };
  },
  methods: {
    async openfile(file) {
      try {
        const response = await axios.get(`/bbjapi/system/systemfile/${file.id}`, {
          responsetype: "blob", // 设置响应类型为 blob
        });
        const blob = new blob([response.data], {
          type: response.headers["content-type"],
        });
        const url = window.url.createobjecturl(blob);

        // 根据文件类型设置预览方式
        const lowercaseinput = file.name.tolowercase();
        if (this.imageextensions.some((ext) => lowercaseinput.endswith("." + ext))) {
          // 如果是图片类型,创建弹窗进行预览
          this.createimagemodal(url);
        } else {
          // 其他类型的文件直接下载
          this.downloadfile(url, file.name);
          window.url.revokeobjecturl(url); // 释放对象 url
        }

      } catch (error) {
        this.$message.error("打开文件异常,请联系管理员");
      }
    },
    createimagemodal(url) {
      // 创建弹窗容器
      const modalcontainer = document.createelement("div");
      modalcontainer.style.position = "fixed";
      modalcontainer.style.top = "0";
      modalcontainer.style.left = "0";
      modalcontainer.style.width = "100%";
      modalcontainer.style.height = "100%";
      modalcontainer.style.backgroundcolor = "rgba(0, 0, 0, 0.7)";
      modalcontainer.style.zindex = "9999";
      modalcontainer.style.display = "flex";
      modalcontainer.style.justifycontent = "center";
      modalcontainer.style.alignitems = "center";

      // 创建图片元素
      const imgelement = document.createelement("img");
      imgelement.src = url;
      imgelement.style.maxwidth = "80%";
      imgelement.style.maxheight = "80%";

      // 创建关闭按钮
      const closebutton = document.createelement("button");
      closebutton.textcontent = "关闭";
      closebutton.style.position = "absolute";
      closebutton.style.top = "10px";
      closebutton.style.right = "10px";
      closebutton.style.padding = "5px 10px";
      closebutton.style.backgroundcolor = "#409eff";
      closebutton.style.border = "none";
      closebutton.style.cursor = "pointer";
      closebutton.style.borderradius = "10px";
      closebutton.style.color = "#fff";

      // 点击关闭按钮时移除弹窗
      closebutton.addeventlistener("click", () => {
        document.body.removechild(modalcontainer);
        window.url.revokeobjecturl(url); // 释放对象 url
      });

      // 将图片和关闭按钮添加到弹窗容器中
      modalcontainer.appendchild(imgelement);
      modalcontainer.appendchild(closebutton);

      // 将弹窗容器添加到页面主体中
      document.body.appendchild(modalcontainer);
    },
    downloadfile(url, filename) {
      // 创建下载链接
      const link = document.createelement("a");
      link.href = url;
      link.setattribute("download", filename);
      document.body.appendchild(link);
      link.click();
      document.body.removechild(link);
    },
    handlefilesuccess(response, file, filelist) {
      // 处理文件上传成功的回调
      console.log("文件上传成功", response);
    },
    handlefileremove(file, filelist) {
      // 处理文件移除的回调
      console.log("文件移除", file);
    },
    handlefileerror(error, file, filelist) {
      // 处理文件上传失败的回调
      console.error("文件上传失败", error);
    },
  },
};
</script>

<style>
/* 可以根据需要添加样式 */
</style>

1.2 组件说明

  • el-upload 组件配置:配置了文件上传的基本参数,如上传地址、成功、移除和失败的回调函数等。
  • openfile 方法:异步方法,根据文件类型进行预览或下载。如果是图片类型,则创建一个模态框显示图片;否则,直接下载文件。
  • createimagemodal 方法:创建图片预览的模态框,包括显示图片和关闭按钮。
  • downloadfile 方法:创建下载链接并进行下载。

2.注意事项

  • blob 对象:用于处理从服务器获取的二进制数据,如图片内容。
  • 文件类型判断:通过文件后缀名判断文件类型,这里示例了图片类型的判断方式。

通过以上方法,你可以在 vue.js 项目中利用 element ui 的 el-upload 组件实现文件上传并根据文件类型进行预览或下载的功能。这样的实现不仅提升了用户体验,还增加了系统的交互性和可用性。

总结

到此这篇关于vue如何实现文件预览和下载功能的前端上传组件的文章就介绍到这了,更多相关vue文件预览和下载功能内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com