Arya
Arya

Reputation: 8985

Save image from url with HTMLUnit

Is it possible to save an image to hard disk with HTMLUnit by giving it the image URL? If so how?

Regards!

Upvotes: 11

Views: 10168

Answers (2)

2010jing
2010jing

Reputation: 13

Here is how I wrote the code like this:

NodeList nlx = downloadPage.getElementsByTagName("a");
for (int y = 0; y<nlx.getLength(); y++) {
    String ss = nlx.item(y).toString();
    if(ss.contains("download/?fileformat=kml")) {
        System.out.println(ss);
        HtmlElement anchorAttachment = (HtmlElement)nlx.item(y);
        InputStream is =anchorAttachment.click().getWebResponse().getContentAsStream();
        try {
            //System.out.println(is);
            OutputStream out = new FileOutputStream(new File(fileName+".KML"));

            int read=0;
            byte[] bytes = new byte[1024];
            while((read = is.read(bytes))!= -1) {
                out.write(bytes, 0, read);
            }
            is.close();
            out.flush();
            out.close();    
            System.out.println("New file created!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

Upvotes: 0

Mosty Mostacho
Mosty Mostacho

Reputation: 43434

If you're using HtmlUnit then you should have an HtmlPage. There you can get an HtmlImage and save the file this way:

HtmlImage image = page.<HtmlImage>getFirstByXPath("//img[@src='blah']");
File imageFile = new File("/path/to/file.jpg");
image.saveAs(imageFile);

If you do have an URL... then I don't think you need HtmlUnit to download the image.

Upvotes: 14

Related Questions