vue中对pdf文件和路径的处理

根据url预览pdf文件

地址栏输入url可以直接预览的pdf,这种我们可以直接使用vue-pdf进行预览

<div class="animation-box-pdf">
 	<pdf :src="url" />
 </div>

<script>
import Pdf from 'vue-pdf'

export default {
  components: {
    Pdf,
  },
  data() {
    return {
      url: 'http://xxx/xxx/test.pdf',
    }
  },
  methods: {
  }
}

把文件的url地址转成base64字符串

有时候我们拿到了文件的url,需要把这个url的文件内容转成base64字符串,作为参数传给后端

async handleUrlToBase64(type) {
      // 把文件的url地址转成base64字符串
      
      const fileBase64 = await new Promise((resolve) => {
        // 使用Fetch API获取PDF文件内容
        fetch('https://example.com/path.pdf')
          .then(response => response.blob()) // 将响应转换为Blob对象
          .then(blob => {
    	    // 使用FileReader读取Blob并转换为base64字符串
            let reader = new FileReader();
            reader.onload = function() {
              // 注意:这个地方的base64是截取了,后面的字符串的,需要注意是否截取字符串
              resolve(reader.result.split(',')[1]); // 转换后的base64字符串
            };
            reader.readAsDataURL(blob); // 以DataURL形式读取Blob
          })
        .catch(error => {
          this.$YsMessage.error("文件解析失败");
        });
      });
      
      console.log(fileBase64) // base64字符串
      // 调接口传base64字符串
    },
  },

根据返回的文件流预览pdf文件

后端接口返回的是文件流,我们需要将文件流预览到页面展示。

注意:接口返回文件流的话,接口中需要加{ responseType: 'blob' }请求头

我们将文件流转成url,并预览url(预览就可以直接使用url借助vue-pdf进行预览了)

    handleBinaryToUrl(binary) {
      const url = window.URL.createObjectURL(
        new Blob(binary, {
          type: "application/pdf;charset=utf-8",
        })
      );
      this.url = url;
    },

把文件流上传到服务器,把上传后的路径传给后端\

需要将文件流转成blob上传

// const blob = new Blob([pdfFileStream], { type: 'application/pdf;charset=utf-8' });
const formData = new FormData();
const fileName = `test.pdf`;
formData.append('file', this.blob, fileName);
fetch('/api/upload', {
  method: 'post',
  body: formData
})
.then(res => {
  const filePath = `webDownLoad/xxxx/${fileName}`;
  // 将filePath传给后端
})
.catch(err => {
})
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值