ZK7.0.3中从MongoDB下载文件

问题

在完成Spring从MongoDB中下载文件之GridFS之后,现在需要在ZK7.0.3的ViewModel中下载该文件。

思路

先从MongoDB获取到OutputStream,以及把OutputStream转化为ZK的Filedownload能够使用的InputStream进行文件下载。

实现

导入Filedownload

import org.zkoss.zul.Filedownload;

ViewModel

String fileId = "5602de6e5d8bba0d6f2e45e4";
// 从Mongod中查找出一个文件,注意这里返回为com.mongodb.client.gridfs.model.GridFSFile类
GridFSFile gridFsdbFile = operations.findOne(new Query(Criteria.where("_id").is(fileId)));
if (gridFsdbFile != null) {
        // mongo-java-driver3.x以上的版本就变成了这种方式获取
        GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 获取Mongodb中文件的缓存输出流
        bucket.downloadToStream(gridFsdbFile.getId(), baos);
        Document meteData = gridFsdbFile.getMetadata();
        // 将OutputStream缓存流转化为InputStream缓存流使用
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        // 下载文件
        if(meteData != null) {
                Filedownload.save(bais, meteData.get("contentType").toString(), gridFsdbFile.getFilename());
        } else {
                Filedownload.save(bais, null, gridFsdbFile.getFilename());
        }
}

**Note:**这里主要的问题其实转化为Java的流转化了。JavaOutputStream流转化InputStream流方式很多,主要三种:

  • 使用缓存流转化
  • 使用管道流转化
  • 使用循环缓存流转化

缓存流:

ByteArrayOutputStream out = new ByteArrayOutputStream();
class1.putDataOnOutputStream(out);
class2.processDataFromInputStream(
  new ByteArrayInputStream(out.toByteArray())
);

管道流

PipedInputStream in = new PipedInputStream();
PipedOUtputStream out = new PipedOutputStream(in);
new Thread(
  new Runnable(){
    public void run(){
      class1.putDataOnOutputStream(out);
    }
  }
).start();
class2.processDataFromInputStream(in);

循环流

// 多线程方式
CircularByteBuffer cbb = new CircularByteBuffer();
new Thread(
  new Runnable(){
    public void run(){
      class1.putDataOnOutputStream(cbb.getOutputStream());
    }
  }
).start();
class2.processDataFromInputStream(cbb.getInputStream());
// 单线程方式
// buffer all data in a circular buffer of infinite size
CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE);
class1.putDataOnOutputStream(cbb.getOutputStream());
class2.processDataFromInputStream(cbb.getInputStream());

总结

主要是使用ZK的Filedownload进行文件下载,但是ZK的Filedownload需要InputStream支持,所以,就涉及到了OutputStream转InputStream操作。

参考: Convert a Java OutputStream to an InputStream Class Filedownload

转载于:https://my.oschina.net/fxtxz2/blog/1828917

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值