将图像从URL保存到postgresql数据库

时间:2015-08-01 22:15:38

标签: java sql postgresql

我找到了将图像保存到磁盘然后保存到数据库的示例,但是我找不到任何保存到数据库而不保存到磁盘的示例。

任何例子都会受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

您需要读取URL并使用字节数组存储它。之后,您可以从中创建一个ByteArrayInputStream并将其保存在数据库中:

        URL someUrl = null;
        try{
            someUrl = new URL("http://www.oracle.com/");
        }catch(IOException ex){
            //TODO: log error
        }

        if(someUrl != null){
            byte[] arr = null;
            try(InputStream is = someUrl.openStream()){
                arr = readBytesFromStream(is);
            }catch(IOException ex){
                //TODO: log error
            }
            InputStream anotherStream = new BufferedInputStream(new ByteArrayInputStream(arr));
            PreparedStatement stmt = createStatement();
            stmt.setBinaryStream(index, anotherStream, arr.length);
            stmt.execute();
        }

我通过使用readBytesFromStream和createStatement函数简化了一下,但我认为你明白了。

相关问题