从URL加载图像并限制文件的大小

时间:2011-12-14 16:02:15

标签: java image url download

我已经找到了如何在SO上使用此问题从网址加载图片:how to load a image from web in java

但是我想限制正在加载的文件的大小,因为所有答案都有这个共同点:如果用户将url提供给1 TB的文件,它将崩溃我的服务器:/

如何限制正在下载的文件的大小?

感谢您的帮助! :)

4 个答案:

答案 0 :(得分:5)

按照您之前的答案获得的代码......

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

您可以在此处找到有关URLConnection()方法的更多信息。

请注意,这只会尊重另一端提供的HTTP标头,没有理由遵守或诚实。因此,如果你正在玩真正的安全和“不要黑客攻击”的一面,你应该检查InputStream即将到来并在固定数量的数据后终止它。

答案 1 :(得分:3)

如果您希望保证您不会下载超过一定金额,则需要使用您自己的实现包装InputStream。基本上创建一个新类

/**
 * 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);
    }
}

然后像这样使用那个类:

ImageIO.read(new InputStreamLimiter(new URL("http://server/image.png").openStream(),MAX_BYTES)));

答案 2 :(得分:1)

保证您不会下载大文件的更简单方法是使用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"));

答案 3 :(得分:0)

我认为你可以在InputStream上使用“mark”方法并设置readlimit。