Jackrabbit文件存储

时间:2015-10-12 18:03:52

标签: jackrabbit

我想测试使用Apache Jackrabbit保存和检索文件。当我以后无法检索时,我不确定它是否可以保存。以下是我的代码。我的问题是如何检索我保存的文件。

@Test
public void storeFile() throws Exception {
    File file = getFile();
    FileInputStream fileInputStream = new FileInputStream(file);

    Repository repository = new TransientRepository(); 
    Session session = repository.login( 
    new SimpleCredentials("username", "password".toCharArray())); 
    try { 
        logger.info("logged in as user '{}'", session.getUserID());
        Node root = session.getRootNode(); 

        // Store content 
        Node hello = root.addNode("userid_12"); 
        Node world = hello.addNode("files"); 


        logger.debug("setting fileInputStream");
        world.getSession().getValueFactory().createBinary(fileInputStream);

        session.save(); 

        // Retrieve content 
        Node node = root.getNode("userid_12/files"); 
        logger.info(node.getPath()); 
        //how do I retrieve the file now?
      }

1 个答案:

答案 0 :(得分:2)

刚刚做了类似的事情,并使用了示例页面(http://wiki.apache.org/jackrabbit/ExamplesPage)来完成它。

你需要告诉jackrabbit节点类型,并在保存时传递二进制数据和mime类型,如下所示:

Node DocNode = currentDocNode.addNode(doc.getFilename(),"nt:file");
    Node contentNode = DocNode.addNode("jcr:content","nt:resource");
    Binary binary = session.getValueFactory().createBinary(file.getInputStream());
    contentNode.setProperty("jcr:data",binary);
    contentNode.setProperty("jcr:mimeType",file.getContentType());
    Calendar created = Calendar.getInstance ();
    contentNode.setProperty("jcr:lastModified", created);

这将在节点中正确保存文档。然后检索文件只是获取节点并读取数据,有一个JcrUtils类为您执行此操作:

Node fileNode = root.getNode("path/to/node");
InputStream stream = null;
if(null != fileNode){
 stream = JcrUtils.readFile(fileNode);
}

然后你可以使用inputStream做什么(将它传递给响应等)