I have found how to load an image from an URL using this question on SO : how to load a image from web in java
But I'd like to limit the size of the file being loaded because all the answers have this in common : if a user give the URL to a one terabyte file, it will crashes my server :/
How can I limit the size of the file being downloaded ?
An easier way to guarantee you won't download a large file is to use IOUTils.read:
int maxDownload = 1024*1024*2;
URL website = new URL("http://www.wswd.net/testdownloadfiles/200MB.zip");
byte[] outBytes = new byte[maxDownload];
InputStream stream = website.openStream();
IOUtils.read(stream, outBytes, 0, maxDownload);
if (stream.read() != -1) {
System.out.println("File too big");
}
IOUtils.write(outBytes, new FileOutputStream("200MB.zip"));