PDF文件上传转成base64编码并支持预览

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。PDF文件上传转成base64编码并支持预览,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

在工作中,有个需求,前端上传PDF文件,需要转成base64编码,传给后端。查看的时候,后端返回base64编码,前端实现PDF预览。

具体实现代码如下:

<template>
  <div>
    <!-- 选择文件 -->
    <el-upload
      :multiple="false"
      accept=".pdf"
      action="#"
      :http-request="httpRequest"
      :show-file-list="false"
    >
      <el-button size="mini" type="primary">点击上传</el-button>
    </el-upload>

    <!-- 文件列表 -->
    <el-table :data="files" style="width: 100%">
      <el-table-column type="index" width="100"> </el-table-column>
      <el-table-column prop="fileName" label="文件名称"> </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            @click="lookFile(scope.row.fileId)"
            type="text"
            size="small"
            >查看</el-button
          >
          <el-button @click="delFile(scope.index)" type="text" size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 文件预览 -->
    <el-dialog title="文件预览" :visible.sync="dialogVisible" width="1000px">
      <div style="height: 80vh">
        <iframe
          width="100%"
          height="100%"
          :src="`data:application/pdf;base64, ${file}`"
        ></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false, //预览弹窗
      file: "", //预览文件
      files: [], //已上传的文件列表
    };
  },
  methods: {
    //删除
    delFile(index) {
      this.files.splice(index, 1);
    },

    //预览
    lookFile(fileId) {
      let that = this;
      //这里调用后端接口,根据自己项目修改,传递参数为fileId
      this.$api
        .getFile({ fileId })
        .then((res) => {
          if (res.data.code == 200) {
            //这里是接口返回的文件base64,不带data:application/pdf;base64, 前缀
            that.file = res.data.data;
            that.dialogVisible = true;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //覆盖默认的上传行为,可以自定义上传的实现
    httpRequest(data) {
      // 调用转方法base64
      this.getBase64(data.file)
        .then((resBase64) => {
          //获取文件,不带data:application/pdf;base64, 前缀
          this.file = resBase64.split(",")[1];
          //获取文件名称
          this.fileName = data.file.name;
          //调用上传接口
          that.upload();
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //调用接口上传文件
    upload() {
      let that = this;
      let { file, fileName } = that;
      //这里调用后端接口,根据自己项目修改,传递参数为base64文件,及文件名称
      this.$api
        .upload({ file, fileName })
        .then((res) => {
          if (res.data.code == 200) {
            let result = res.data.data;
            //这里是接口返回fileId,fileName,然后添加到文件列表数组里
            that.files.push({
              fileId: result.fileId,
              fileName: result.fileName,
            });
            that.$message.success("文件上传成功");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 转base64码
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        let fileResult = "";
        reader.readAsDataURL(file);
        // 开始转码
        reader.onload = () => {
          fileResult = reader.result;
        };
        // 转码失败
        reader.onerror = (error) => {
          reject(error);
        };
        // 转码结束
        reader.onloadend = () => {
          resolve(fileResult);
        };
      });
    },
  },
};
</script>

<style scoped>
iframe {
  border: 0 none;
}
::v-deep .el-dialoog__body {
  padding: 8px !important;
  box-sizing: border-box;
}
</style>

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

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/188397.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!