3

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 ?

Thanks for your help! :)

1
  • "if a user give the url to a one terabyte file, it will crashes my server" Why does it crash your server? Is the resource coming from your server? Is your server acting as a proxy (getting it from another server) for the file? Dec 14, 2011 at 16:20

4 Answers 4

5

Following the code you got from your previous answer...

URL url = new URL("http://host/theimage.jpg");
URLConnection conn = new URLConnection(url);

// now you get the content length
int cLength = conn.getContentLength();

InputStream in = conn.getInputStream();

You can find more on the methods of URLConnection() here.

Do take into consideration that this will honor only the HTTP headers given by the other end, there is no reason it will comply or be honest about it. So if you're playing on the real safe and "do-not-hack-me" side you should inspect the InputStream as it is coming and terminate it after a fixed amount of data.

6
  • The content length is given before downloading ? (in the headers)?
    – Cyril N.
    Dec 14, 2011 at 16:11
  • By the way, I get a "Cannot instantiate the type URLConnection" :/
    – Cyril N.
    Dec 14, 2011 at 16:13
  • @cx42net generally content length is given before. For instance, when you download a file with your browser (a large one) it can give you the percentage remaining (generally with an estimation of the time to complete) or not. If it does give you those number is because the connection on the other end has honored the HTTP headers and sent the length on the headers.
    – Frankie
    Dec 14, 2011 at 16:17
  • and @Jack Edmonds has gone all the way to give you the paranoid solution I was talking about.
    – Frankie
    Dec 14, 2011 at 16:18
  • Perhaps you meant to check that the content-length was less than the maximum number of bytes @cx42net wanted to read (e.g. if (cLength>1000000000000)throw new FileTooBigException();)? Dec 14, 2011 at 16:20
3

If you want to guarantee that you won't download more than a certain amount, you will need to wrap InputStream with your own implementation. Essentially create a new class

/**
 * Limits the amount of data you can read.
 * Warning: this only partially implements all the necessary methods.
 *     You will need to implement the rest that I was too lazy to include.
 */
public class InputStreamLimiter extends InputStream {
    private final InputStream wrappedInputStream;
    private int bytesRead;
    private final maxBytes;
    public InputStreamLimiter(final InputStream stream, final int maxBytes)
    {
        this.maxBytes=maxBytes;
        this.wrappedInputStream=stream;
    }
    public int available(){return wrappedInputStream.available();}
    public void close(){wrappedInputStream.close();}
    //Continue wrapping methods until you reach the read() methods.

    /**
     * Provide your own implementation of the read methods that make sure you don't attempt to read too many bytes.
     * This method crashes if you attempt to read too much.
     */
    public int read(final byte b[]) throws IOException {
        if (b.length + bytesRead > maxBytes) throw new IOException("File was too big.");
        else return wrappedInputStream.read(b);
    }
}

Then use that class like so:

ImageIO.read(new InputStreamLimiter(new URL("http://server/image.png").openStream(),MAX_BYTES)));
1
  • Your answer is really great and interesting, if I could select two answers, ours would have been in, but unforntutaley, the accepted one fit better my needs for now (maybe I'll use yours laters). Thanks again :)
    – Cyril N.
    Dec 14, 2011 at 17:12
1

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"));
0

I think you can use "mark" method on InputStream and set readlimit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.