Web页面预览HDFS上的图片文件

html代码:

<div style="float: left">
    <!-- 图片展示按钮 -->
    <button class="myBtn4">
        确认展示
    </button>
</div>
<div id="d1" class="Z_slider">

</div>

js代码:

细节说明:
// 错误写法 (不可直接将blob加载到img中,由于blob太大,会有性能影响,所以先释放)
var img = document.createElement("img");
img.src = window.URL.createObjectURL(blob);
//正确写法
var img = document.createElement("img");
img.onload = function(e) {
	window.URL.revokeObjectURL(img.src); //释放
};
img.src = window.URL.createObjectURL(blob);
$("#d1").html(img);
$(function() {
    $('.myBtn4').on('click', function(){
        var url = "/项目名/homepage/showPic";
        var xhr = new XMLHttpRequest(); //创建 XMLHttpRequest 对象
        xhr.open('POST', url, true);
        xhr.responseType = "blob";
        xhr.setRequestHeader("client_type", "DESKTOP_WEB");
        xhr.onload = function() {
            if (this.status == 200) {
                var blob = this.response;
                var img = document.createElement("img");
                img.onload = function(e) {
                    window.URL.revokeObjectURL(img.src);//释放
                };
                img.src = window.URL.createObjectURL(blob);
                $("#d1").html(img);
            }
        }
        xhr.send();
     })
 })

java代码:

@Override
    public void showPic(HttpServletRequest request, HttpServletResponse response) throws URISyntaxException, IOException, InterruptedException {
        Configuration conf = new Configuration();
        String uri="hdfs://192.168.248.147:9000/yttlj/input/2.jpg";
        Path _file = new Path(uri);
        FileSystem hdfs = FileSystem.get(URI.create(uri),conf, "root");
        FileStatus status = hdfs.getFileStatus(_file);
        //获取输入流
        FSDataInputStream fis = hdfs.open(_file);
        response.setHeader("Content-Type", "image/jpeg");
        response.setHeader("Content-Length", String.valueOf(status.getLen()));

        BufferedOutputStream output = null;
        output = new BufferedOutputStream(response.getOutputStream());

        byte [] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fis.read(buffer)) > 0) {
            output.write(buffer, 0, bytesRead);
        }
        //使用 BufferedOutputStream 最后要利用 flush 将 buffer 数据送出去
        output.flush();
        fis.close();
    }

结果展示:
在这里插入图片描述

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值