-2

Is there any way to get the type(format) of the uploading file in java.?

iam able to upload the file of any format .now want to get the file type to be stored into database.

One more thing i dont have file_type field column in the upload form.Have file_type field column only in the database..please help me

thanks all..

praveen
  • 17
  • 1
  • 1
  • 9

1 Answers1

0

You can get the extension by using substring starting from 1+ the index of the last . (if present) in the string

Use java.nio.file.Files.probeContentType to determine the MIME type of the file. It returns a String which should be useful for you. From the docs:

public static String probeContentType(Path path) throws IOException

Probes the content type of a file.

This method uses the installed FileTypeDetector implementations to probe the given file to determine its content type. Each file type detector's probeContentType is invoked, in turn, to probe the file type. If the file is recognized then the content type is returned. If the file is not recognized by any of the installed file type detectors then a system-default file type detector is invoked to guess the content type.

A given invocation of the Java virtual machine maintains a system-wide list of file type detectors. Installed file type detectors are loaded using the service-provider loading facility defined by the ServiceLoader class. Installed file type detectors are loaded using the system class loader. If the system class loader cannot be found then the extension class loader is used; If the extension class loader cannot be found then the bootstrap class loader is used. File type detectors are typically installed by placing them in a JAR file on the application class path or in the extension directory, the JAR file contains a provider-configuration file named java.nio.file.spi.FileTypeDetector in the resource directory META-INF/services, and the file lists one or more fully-qualified names of concrete subclass of FileTypeDetector that have a zero argument constructor. If the process of locating or instantiating the installed file type detectors fails then an unspecified error is thrown. The ordering that installed providers are located is implementation specific.

The return value of this method is the string form of the value of a Multipurpose Internet Mail Extension (MIME) content type as defined by RFC 2045: Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies. The string is guaranteed to be parsable according to the grammar in the RFC.

Parameters: path - the path to the file to probe Returns: The content type of the file, or null if the content type cannot be determined Throws: IOException - if an I/O error occurs SecurityException - If a security manager is installed and it denies an unspecified permission required by a file type detector implementation.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175