美文网首页
一次前后端互动实现图片查看器功能

一次前后端互动实现图片查看器功能

作者: 江江简书 | 来源:发表于2019-12-15 12:35 被阅读0次
在以前的项目中实现存在ftp中的图片的预览效果只能是通过window.open的方式预览,这样就无法实现图片旋转等特殊的功能一直诟病着项目

1.先上效果图


image.png
image.png

2.本次实现是用php后端返回二进制流文件及前端XMLHttpRequest以及viewjs来实现

3.源码

//1.后端源码php
ob_end_clean();
ob_start();
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
//这里$file_size获取文件长度
header("Accept-Length: ".$file_size);
//这里要传入ftp的url
header("Content-Disposition: attachment; filename=" . basename( $ftp_link));

$buffer=1024;
$buffer_count=0;
//循环主要是为了大文件读取
    while(!feof($handler) && $file_size-$buffer_count>0){
        $data = fread($handler, $buffer);//$handler是文件打开的锚
        $buffer_count += $buffer;
        echo $data;
    }
    fclose($handler);
    ob_end_flush();
    exit;
//1.前端源码实现
 var id_attachment = id_att;
        var url = 这里传入上面php文件的地址;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = "blob";
        xhr.filename=id_attachment;
        xhr.onload = function () {
            if (this.status == 200) {
                //接受二进制文件流
                var blob = this.response;
              //下面主要是为了给id给定src要传入不同的id否则会无效
$("#imgcontainer"+id_attachment).attr('src',window.URL.createObjectURL(blob));
                $('#imgcontainer'+id_attachment).viewer({
                });
            }
        };
        xhr.send();

至于前面表格显示预览图效果是通过datatable的createdRow来实现,这个目前实现的只有jpg和png的渲染pdf貌似也不需要这样旋转,或者技术还没有到这个层次如果你有更好的想法或者有想和我切磋的尽管留言

相关文章

网友评论

      本文标题:一次前后端互动实现图片查看器功能

      本文链接:https://www.haomeiwen.com/subject/qomknctx.html