Files Probe Content Type For Uploads

Detect upload MIME types with Files.probeContentType and treat the null result as unknown, since the mapping comes from the system file-type table.

JavaFile Upload

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class UploadTypeProbe {

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("upload-");
        // The content-type mapping comes from the operating system's file-type table; no third-party MIME library needed
        Path pdf = Files.writeString(dir.resolve("invoice.pdf"), "%PDF-1.7 fake bytes");
        Path log = Files.writeString(dir.resolve("server.log"), "INFO started");

        System.out.println("invoice.pdf -> " + Files.probeContentType(pdf));
        System.out.println("server.log -> " + Files.probeContentType(log));

        // Unprobeable files return null: upload validation must treat null as an unknown type, not wave it through
        Path unknown = Files.writeString(dir.resolve("README"), "no extension here");
        System.out.println("README -> " + Files.probeContentType(unknown));

        // Allowlist check: MIME is only a hint, so the server confirms against extension and content as well
        String pdfType = Files.probeContentType(pdf);
        if ("application/pdf".equals(pdfType)) {
            System.out.println("accepted as pdf");
        } else {
            System.out.println("type unresolved or rejected: " + pdfType);
        }
    }
}

What the code does

All of the logic lives in the class UploadTypeProbe.

Watch out for

  • Nothing to add to the project before running it.

Using it

Each run prints the 5 labeled blocks invoice.pdf ->, server.log ->, README ->, accepted as pdf, type unresolved or rejected: in source order.

Key statements

Path pdf = Files.writeString(dir.resolve("invoice.pdf"), "%PDF-1.7 fake bytes");
Path unknown = Files.writeString(dir.resolve("README"), "no extension here");
Path log = Files.writeString(dir.resolve("server.log"), "INFO started");

Interactive Tools for This Topic

FAQ

What does Files Probe Content Type For Uploads print when run?
Running the file directly is enough — expect labeled output lines such as `invoice.pdf ->`, `server.log ->`, `README ->`.