0

I have found examples for saving images to disk then to the database, but I can not find any examples to save to database without saving to disk.

Any example would be highly appreciated.

Arya
  • 8,473
  • 27
  • 105
  • 175
  • possible duplicate of [Store and retrieve images in Postgresql using Java](http://stackoverflow.com/questions/15127100/store-and-retrieve-images-in-postgresql-using-java) – Patrick Aug 02 '15 at 12:29
  • No it isn't. Arya asked for storing data directly from an URL without having a local file. The solution i provided fits that use-case perfectly. ;) – ChrisKo Aug 02 '15 at 12:40

1 Answers1

0

You need to read the URL and store it using a byte-array. after that you can create a ByteArrayInputStream from it and save it in the Database:

        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();
        }

I simplified it a bit by using the functions readBytesFromStream and createStatement, but i think you get the idea.

ChrisKo
  • 365
  • 2
  • 8
  • Thanks for your answer, but in eclipse its saying that "readBytesFromStream(InputStream)" is undefined. I have imported java.io.InputStream; – Arya Aug 02 '15 at 18:06