通过文件流接口预览图片与PDF

2022/11/29 blob

当后台提供接口返回非文件地址而是文件流时如何直接预览

# 图片

直接拼接请求地址 传入src 即可


# PDF

$.ajax不可以直接请求文件流

    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true); // 也可以使用POST方式,根据接口
    xhr.setRequestHeader('Content-Type', 'application/octet-stream');
    xhr.responseType = 'blob'; // 返回类型blob
    xhr.onload = function(e) {
        if (this.status === 200) {
            let blob1 = new Blob([this.response],{
                type: 'application/pdf;charset=utf-8'
            })
            //获取响应头上的文件名称
            let  fileName = decodeURI(
                xhr?.getResponseHeader('content-disposition')?.split(';')[1].split('=')[1] || '',
              );
            let src1 = window.URL.createObjectURL(blob1)
            //将src1 传入插件需要的预览地址即可;
        }
    };
    xhr.send(); // 发送ajax请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
最后更新时间: 2023/1/12 15:59:09