Wednesday, December 16, 2015

Determining image file size in Javascript

After a lot of googling and searching, I realized the best way to do this is to create a service call to the backend witht he url of the image whose size needs to be figured out.

This service should make a HEAD call to the server to get the content - length. And pass it along as a response.

Not all servers support HEAD calls so as a fallback make a GET call to the get the request and determine the file size from the headers.

We need to set few headers for this to work universally. One of them is user-agent.

Code for the same is :

private void makeRequest(@FormParam("url") String url, Map response, String requestMethod) {
    try {
        HttpURLConnection urlCon =
                (HttpURLConnection) new URL(url).openConnection();
        urlCon.setRequestMethod(requestMethod);
        urlCon.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0");
        //urlCon.setDoOutput(true);        urlCon.setDoInput(true);
        urlCon.setUseCaches(false);
        urlCon.setDefaultUseCaches(false);
        urlCon.setConnectTimeout(2*60*1000); // 2 minute        urlCon.setReadTimeout(5*60*1000); // 5 minute
        if(urlCon.getResponseCode() == HttpURLConnection.HTTP_OK)
        {
            String contentLength =  urlCon.getContentLengthLong()+"";
            String contentType = urlCon.getContentType();
            response.put("content-length",contentLength);
            response.put("content-type",contentType);
            response.put("status","ok");
        }
        else        {
            response.put("status","nok");
        }
    }
    catch (Exception e)
    {
        e.printStackTrace();
        response.put("status","nok");
    }
}