Monday, January 5, 2015

Guessing file content type

You can get file content type from a URL as following:

String fileUrl = "http://example.com/myimage.jpg";
String contentType = URLConnection.guessContentTypeFromName(fileUrl);

and the result would be:

image/jpeg

There is another method to guess file content type from input stream instead, URLConnection.guessContentTypeFromStream(InputStream) but if the server does not return content type of the file in the response header when you access it, the method would return null. Guessing content type from file name still work in this case.


No comments:

Post a Comment