在线预览PDF文件、图片,并且预览地址不显示文件或图片的真实路径。

5 篇文章 0 订阅
1 篇文章 0 订阅

1、vue使用blob流在线预览PDF、图片(包括jpg、png等格式)。

想要实现在线预览PDF文件、图片,并且预览地址不显示文件或图片的真实路径,可使用blob流。

vue前端关键代码:

1、按钮的方法:

<el-button color="#00ffcc" size="small" @click="invoicePreview(props.row.oid)" v-if="props.row.ifInvoice == 1"><el-icon><Tickets /></el-icon>查看发票</el-button>

2、方法详细:(此方法可以在发起请求时携带token,适合JWT认证)

// 预览发票
invoicePreview(oid){
                console.log(oid)
                this.$http({
                    url: 'invoicePreview',
                    method: 'get',
                    responseType: 'arraybuffer',
                    params: {
                        oid: oid
                    }
                }).then(res => {
                    console.log(res);
                    console.log(res.headers.type);

                    let fileType = res.headers.type;
                    let currType = '';

                    const binaryData = [];
                    if(fileType){
                        currType = fileTypeMap[fileType]
                        if(this.imageType.includes(fileType)){
                            // 识别为图片
                            binaryData.push(res.data);
                            //获取blob链接
                            this.URL = window.URL.createObjectURL(new Blob(binaryData, {type: currType}));
                            window.open(this.URL);
                        }else if(this.wordType.includes(fileType)){
                            // 识别为PDF
                            binaryData.push(res.data);
                            //获取blob链接
                            this.URL = window.URL.createObjectURL(new Blob(binaryData, {type: currType}));
                            window.open(this.URL);
                        }else {
                            this.$message.error('不支持此文件预览')
                        }
                    }else {
                        this.$message.error('不支持此文件预览')
                    }
                })
            }

3、script中定义一些指定格式使用blob转换的文件类型:

const fileTypeMap = {
        "pdf": "application/pdf",
        "png": "image/png",
        "gif": "image/gif",
        "jpeg": "image/jpeg",
        "jpg": "image/jpeg",
        "txt": "txt/plain",
    }

4、export default 中data ( ) 设置文件类型数组包含何种文件格式:

作用是与blob转换的文件类型进行匹配。

data () {
            return {
                wordType:['pdf', 'txt'],
                imageType: ['png', 'gif', 'jpeg', 'jpg']
            }

在这里插入图片描述

2、springboot后端接口返回文件流。(文件类型放在请求头,以便前端获取处理)

后端关键代码:(二选一即可)

1、方法1:

        File file = new File(filePath);

        //获取文件后缀
        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length());

        //使用流的形式下载文件--方法2
        try (
                InputStream is = new FileInputStream(filePath);
                OutputStream os = response.getOutputStream()
        ) {
            byte[] bytes = StreamUtils.copyToByteArray(is);
            response.reset();
            response.addHeader("Content-Disposition", "inline;filename=" + new String(filePath.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.addHeader("Content-Length", "" + bytes.length);
            // 文件类型放在请求头,以便前端获取处理
            response.addHeader("type", suffix);
            os.write(bytes);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

2、方法2:

        File file = new File(filePath);

        //获取文件后缀
        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length());

        try {
            response.addHeader("Content-Disposition", "inline; filename*=UTF-8''" + URLEncoder.encode(file.getName(), "UTF-8"));
            // 文件类型放在请求头,以便前端获取处理
            response.addHeader("type", suffix);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ServletOutputStream os = null;
        try{
            os = response.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(os != null){
                // 此处的close为一个私有方法
                close(os);
            }
        }
private void close(Closeable closeable){
        if(closeable != null){
            try{
                closeable.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

3、前端最终的展示效果:

在这里插入图片描述
在这里插入图片描述
至此完结!

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
el-upload 组件可以预览 pdf图片,具体方法如下: 1. 引入 pdf.js 和 pdf.worker.js 在 HTML 文件中引入 pdf.js 和 pdf.worker.js 文件,可以从官网下载或者使用 CDN 引入。 ``` <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script> <script src="//mozilla.github.io/pdf.js/build/pdf.worker.js"></script> ``` 2. 设置 el-upload 的 props 在 el-upload 组件中设置 props,包括: - list-type:设置为 "picture-card" 或者 "text",分别表示图片pdf预览方式; - before-upload:在上传之前,使用 pdf.js 预览 pdf 文件; - preview-src-list:图片pdf 文件预览链接。 ``` <template> <el-upload class="upload-demo" action="/upload" :list-type="'picture-card'" :before-upload="handleBeforeUpload" :preview-src-list="previewList"> <i class="el-icon-plus"></i> </el-upload> </template> ``` 3. 编写 handleBeforeUpload 方法 在 methods 中编写 handleBeforeUpload 方法,使用 pdf.js 预览 pdf 文件,将预览链接存储在 previewList 中。 ``` <script> export default { data() { return { previewList: [] }; }, methods: { handleBeforeUpload(file) { const reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = () => { pdfjsLib.getDocument({ data: new Uint8Array(reader.result) }).promise.then(pdf => { pdf.getPage(1).then(page => { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); const viewport = page.getViewport(1.0); canvas.height = viewport.height; canvas.width = viewport.width; page.render({ canvasContext: ctx, viewport: viewport }).promise.then(() => { this.previewList.push(canvas.toDataURL("image/png")); }); }); }); }; return false; } } }; </script> ``` 4. 预览效果 上传图片pdf 文件后,即可在 el-upload 组件中看到预览效果。图片pdf 文件预览链接存储在 previewList 中,可以根据需要进行使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值