前端js打开pdf文件--文件通过浏览器打开,以pdf形式进行预览

通过点击button按钮,触发 @click="openPDF(performance_report)"方法,把对应需要展示的pdf传送到openPDF()方法内,这里的pdf文件格式必须包括id、name、url。

在这里,performance_report为预览的文件:

    <div>
        <el-button type="text" size="mini" @click="openPDF(performance_report)">
            测试报告
        </el-button>
    </div>

<script>
    export default {
    
    
        components: {
    
    },
        data() {
    
    
            return {
    
    
                performance_report: [{
    
    
                    id: null,//文件的id
                    name: "",//文件的名称
                    url: "",//文件的url
                }, ],
            };
        },


        created() {
    
    },
        mounted() {
    
    },

        computed: {
    
    },

        methods: {
    
    
            //打开的文件一般是在后端存储的,从后端取到文件后,把文件传输到openPDF方法,用val接收即可。
            openPDF(val) {
    
    
                axios({
    
    
                    method: "get",
                    url: val[0].url,
                    params: {
    
    
                        fileId: val[0].id,
                    },
                    responseType: "blob",
                }).then((res) => {
    
    
                    console.log("res", res);
                    if (res.status == "500") {
    
    
                        this.$message({
    
    
                            message: "下载失败!",
                            type: "error",
                        });
                        return;
                    }
                    //文件以pdf形式进行预览
                    let blob = new Blob([res.data], {
    
    
                        type: "application/pdf;chartset=UTF-8",
                    });
                    let fileURL = URL.createObjectURL(blob);
                    // this.fileURLOther = fileURL;
                    window.open(fileURL);
                });
            }
        }
    }
</script>

猜你喜欢

转载自blog.csdn.net/qq_39877681/article/details/127842565