← 中文资源

简体中文版本

Files 探测上传文件类型

用 Files.probeContentType 探测上传文件的 MIME 类型:映射来自系统文件类型表,返回 null 视为未知类型,上传校验必须显式处理这种情况再走白名单。

阅读英文原文

实现说明

全部逻辑都在类 UploadTypeProbe中。

使用要点

  • 演示输出是带标签的(invoice.pdf ->、server.log ->、README ->),每个操作都会留下自己的一行标注。

常见问题

运行「Files 探测上传文件类型」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 invoice.pdf ->、server.log ->、README -> 标签标明各步骤。

核心语句

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");

代码示例

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);
        }
    }
}