How to store images to jackrabbit and deliver those images to HTML pages?

落花浮王杯 提交于 2019-12-04 15:44:51

This is the way:

 public class JackRabbitServiceImpl {

        Repository repository = new TransientRepository(); 

        public JackRabbitServiceImpl() throws Exception{
            Session session = repository.login( 
                    new SimpleCredentials("username", "password".toCharArray()));
            try{
                InputStream stream = new BufferedInputStream(JackRabbitServiceImpl.class.getResourceAsStream("red_rose.jpg"));
                Node folder = session.getRootNode(); 
                Node file = folder.addNode("redrose.jpg","nt:file");
                Node content = file.addNode("jcr:content","nt:resource");
                Binary binary = session.getValueFactory().createBinary(stream);
                content.setProperty("jcr:data",binary);
                content.setProperty("jcr:mimeType","image/gif");
                session.save(); 
            }finally{
                session.logout(); 
            }
        }

        public byte[] getContentRose() throws Exception{
            Session session = repository.login( 
                    new SimpleCredentials("username", "password".toCharArray()));
            Node folder = session.getRootNode(); 
            Node file=folder.getNode("redrose.jpg");
            Node content=file.getNode("jcr:content");
            String path = content.getPath();
            Binary bin = session.getNode(path).getProperty("jcr:data").getBinary();
            InputStream stream = bin.getStream();
            return IOUtils.toByteArray(stream);
        }

    }

The servlet

public class TestJackRabbitCdn extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 4158924623219324725L;
    JackRabbitServiceImpl service=null;
    @Override
    public void init(){
        try {
            service=new JackRabbitServiceImpl();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,
    ServletException {
        response.setContentType("image/gif");
        try {
            response.getOutputStream().write(service.getContentRose());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.getOutputStream().flush();
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!