Can now get file type from magic number

This commit is contained in:
cyian-1756 2018-07-22 19:02:06 -04:00
parent cbfd363842
commit 368646145d
2 changed files with 23 additions and 0 deletions

View File

@ -6,9 +6,11 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@ -181,6 +183,17 @@ class DownloadFileThread extends Thread {
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type from stream");
// Try to get the file type from the magic number
byte[] magicBytes = new byte[8];
bis.read(magicBytes,0, 5);
bis.reset();
fileExt = Utils.getEXTFromMagic(magicBytes);
if (fileExt != null) {
saveAs = new File(saveAs.toString() + "." + fileExt);
} else {
logger.error("Was unable to get content type using magic number");
logger.error("Magic number was: " + Arrays.toString(magicBytes));
}
}
}
// If we're resuming a download we append data to the existing file

View File

@ -15,6 +15,7 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.net.URISyntaxException;
import java.net.URL;
@ -731,4 +732,13 @@ public class Utils {
Utils.bytesToHumanReadable(bytesTotal);
}
public static String getEXTFromMagic(byte[] magic) {
if (Arrays.equals(magic, new byte[]{-1, -40, -1, -37, 0, 0, 0, 0})) {
return "jpeg";
} else {
LOGGER.info("Unknown magic number " + Arrays.toString(magic));
}
return null;
}
}