Code Snippet: Validate the size of uploaded file on server side

One way is to write the input stream to server side as a file and then validate that file.   However, the uploading has happened. It will not prevent a user from uploading a huge file and taking up server side’s the bandwidth and hard disk.   

So we must do validation while reading the input stream and abort the uploading right away when size limit is reached. 

	/**
	 * read an input stream to a byte array. Return an exception if the stream
	 * is too long or too short. If it is too long, an exception will be thrown
	 * and the reading will be aborted
	 * 
	 * @param in
	 * @param minSize
	 * @param maxSize
	 * @return
	 * @throws InputTooShortException
	 * @throws InputTooLongException
	 * @throws IOException
	 */
	public static byte[] toByteArrayAndValidSize(InputStream in, long minSize,
			long maxSize) throws InputTooShortException, InputTooLongException,
			IOException {

		@SuppressWarnings("resource")
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];

		long count = 0;
		int n = 0;
		while (-1 != (n = in.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
			if (count > maxSize) {
				throw new InputTooLongException();
			}
		}

		if (count < minSize) {
			throw new InputTooShortException();
		}

		return output.toByteArray();

	}

P.S.: inputStream.available() is not reliable. The javadoc says: "Note that while some implementations of InputStream will return the total number of bytes in the stream, many will not. It is never correct to use the return value of this method to allocate a buffer intended to hold all data in this stream."

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.