蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 JDK 8 本地 HttpServer multipart/form-data 上传、边界解析与安全文件名实测

JAVAWindows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。ExploreFileUploading.java
ExploreFileUploading.java289 行
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ExploreFileUploading {

    static class ParsedPart {
        final String fieldName;
        final String fileName;
        final byte[] data;

        ParsedPart(String fieldName, String fileName, byte[] data) {
            this.fieldName = fieldName;
            this.fileName = fileName;
            this.data = data;
        }
    }

    static String sanitizeFileName(String rawName) {
        if (rawName == null) {
            return "";
        }
        String normalized = rawName.replace('\\', '/');
        int slash = normalized.lastIndexOf('/');
        return slash >= 0 ? normalized.substring(slash + 1) : normalized;
    }

    static String extractParam(String headerLine, String key) {
        String needle = key + "=\"";
        int idx = headerLine.indexOf(needle);
        if (idx < 0) {
            return null;
        }
        int start = idx + needle.length();
        int end = headerLine.indexOf('"', start);
        return end < 0 ? null : headerLine.substring(start, end);
    }

    static List<ParsedPart> parseMultipart(String bodyUtf8, String boundary) {
        List<ParsedPart> parts = new ArrayList<ParsedPart>();
        String delimiter = "--" + boundary;
        String[] segments = bodyUtf8.split(delimiter);
        for (String seg : segments) {
            if (seg.isEmpty() || seg.startsWith("--")) {
                continue;
            }
            if (seg.startsWith("\r\n")) {
                seg = seg.substring(2);
            }
            int sep = seg.indexOf("\r\n\r\n");
            if (sep < 0) {
                continue;
            }
            String headerBlock = seg.substring(0, sep);
            String payload = seg.substring(sep + 4);
            if (payload.endsWith("\r\n")) {
                payload = payload.substring(0, payload.length() - 2);
            }
            String fieldName = extractParam(headerBlock, "name");
            String fileName = extractParam(headerBlock, "filename");
            parts.add(new ParsedPart(fieldName, fileName, payload.getBytes(StandardCharsets.UTF_8)));
        }
        return parts;
    }

    static String sha256Hex(byte[] data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] digest = md.digest(data);
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
        }
        return sb.toString();
    }

    static byte[] readAll(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        int n;
        while ((n = is.read(buf)) != -1) {
            baos.write(buf, 0, n);
        }
        return baos.toByteArray();
    }

    static String[] postRaw(String urlStr, String contentType, byte[] payload) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", contentType);
        OutputStream os = conn.getOutputStream();
        os.write(payload);
        os.flush();
        os.close();
        int status = conn.getResponseCode();
        InputStream stream = status >= 400 ? conn.getErrorStream() : conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        conn.disconnect();
        return new String[]{String.valueOf(status), sb.toString()};
    }

    static String esc(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '"': sb.append("\\\""); break;
                case '\\': sb.append("\\\\"); break;
                case '\b': sb.append("\\b"); break;
                case '\f': sb.append("\\f"); break;
                case '\n': sb.append("\\n"); break;
                case '\r': sb.append("\\r"); break;
                case '\t': sb.append("\\t"); break;
                default:
                    if (c < 0x20) {
                        sb.append(String.format("\\u%04x", (int) c));
                    } else {
                        sb.append(c);
                    }
            }
        }
        return sb.toString();
    }

    static String caseJson(String name, String summary, String expected, String actual) {
        boolean passed = expected.equals(actual);
        return "    {\"name\": \"" + esc(name) + "\", \"summary\": \"" + esc(summary)
                + "\", \"expected\": \"" + esc(expected) + "\", \"actual\": \"" + esc(actual)
                + "\", \"passed\": " + passed + "}";
    }

    static void deleteRecursively(File f) {
        if (f.isDirectory()) {
            File[] children = f.listFiles();
            if (children != null) {
                for (File c : children) {
                    deleteRecursively(c);
                }
            }
        }
        f.delete();
    }

    public static void main(String[] args) throws Exception {
        final Path tempRoot = Files.createTempDirectory("servlet-upload-lab-");
        final Path uploadDir = tempRoot.resolve("upload");
        Files.createDirectories(uploadDir);

        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
        server.createContext("/UploadServlet", (HttpExchange ex) -> {
            String ct = ex.getRequestHeaders().getFirst("Content-Type");
            if (ct == null || !ct.toLowerCase().startsWith("multipart/form-data")) {
                byte[] err = "Error: 表单必须包含 enctype=multipart/form-data".getBytes(StandardCharsets.UTF_8);
                ex.getResponseHeaders().add("Content-Type", "text/plain; charset=UTF-8");
                ex.sendResponseHeaders(400, err.length);
                OutputStream os = ex.getResponseBody();
                os.write(err);
                os.close();
                return;
            }
            String boundary = ct.substring(ct.indexOf("boundary=") + "boundary=".length()).trim();
            byte[] raw = readAll(ex.getRequestBody());
            List<ParsedPart> parts = parseMultipart(new String(raw, StandardCharsets.UTF_8), boundary);
            List<String> saved = new ArrayList<String>();
            Map<String, String> fields = new LinkedHashMap<String, String>();
            for (ParsedPart part : parts) {
                if (part.fileName != null) {
                    String safeName = sanitizeFileName(part.fileName);
                    Path target = uploadDir.resolve(safeName);
                    Files.write(target, part.data);
                    saved.add(part.fieldName + ":" + safeName + ":" + part.data.length);
                } else {
                    fields.put(part.fieldName, new String(part.data, StandardCharsets.UTF_8));
                }
            }
            String resp = "ok|fields=" + fields.toString() + "|saved=" + saved.toString();
            byte[] out = resp.getBytes(StandardCharsets.UTF_8);
            ex.getResponseHeaders().add("Content-Type", "text/plain; charset=UTF-8");
            ex.sendResponseHeaders(200, out.length);
            OutputStream os = ex.getResponseBody();
            os.write(out);
            os.close();
        });
        server.start();
        int port = server.getAddress().getPort();
        List<String> cases = new ArrayList<String>();

        try {
            // Case 1: Reject non-multipart Content-Type
            String[] badResp = postRaw(
                    "http://127.0.0.1:" + port + "/UploadServlet",
                    "application/x-www-form-urlencoded",
                    "uploadFile=demo.txt".getBytes(StandardCharsets.UTF_8)
            );
            String act1 = "status=" + badResp[0] + "|hasMultipartError=" + badResp[1].contains("multipart/form-data");
            String exp1 = "status=400|hasMultipartError=true";
            cases.add(caseJson("multipart_content_type_guard", "校验非 multipart/form-data 请求被服务端拦截并返回提示", exp1, act1));

            // Case 2: Single file + form field multipart upload with UTF-8 filename and SHA-256 verification
            String boundary = "----BlueSkyBoundary2026";
            String fileContent = "Servlet multipart upload line 1\n中文上传正文";
            String multipartBody = "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"description\"\r\n\r\n"
                    + "quarterly-note\r\n"
                    + "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"uploadFile\"; filename=\"report-测试.txt\"\r\n"
                    + "Content-Type: text/plain; charset=UTF-8\r\n\r\n"
                    + fileContent + "\r\n"
                    + "--" + boundary + "--\r\n";
            String[] upResp = postRaw(
                    "http://127.0.0.1:" + port + "/UploadServlet",
                    "multipart/form-data; boundary=" + boundary,
                    multipartBody.getBytes(StandardCharsets.UTF_8)
            );
            byte[] storedBytes = Files.readAllBytes(uploadDir.resolve("report-测试.txt"));
            boolean hashMatch = sha256Hex(fileContent.getBytes(StandardCharsets.UTF_8)).equals(sha256Hex(storedBytes));
            String act2 = "status=" + upResp[0] + "|hashMatch=" + hashMatch + "|bytes=" + storedBytes.length + "|" + upResp[1];
            String exp2 = "status=200|hashMatch=true|bytes=50|ok|fields={description=quarterly-note}|saved=[uploadFile:report-测试.txt:50]";
            cases.add(caseJson("multipart_upload_end_to_end", "通过本地 HttpServer 实测 multipart/form-data 表单上传、落盘与 SHA-256 校验", exp2, act2));

            // Case 3: Upload threshold constants & filename path-traversal sanitization
            int memoryThreshold = 1024 * 1024 * 3;
            int maxFileSize = 1024 * 1024 * 40;
            int maxRequestSize = 1024 * 1024 * 50;
            String cleanUnix = sanitizeFileName("../../etc/note.txt");
            String cleanWin = sanitizeFileName("C:\\fakepath\\demo.png");
            String act3 = "mem=" + memoryThreshold + "|maxFile=" + maxFileSize + "|maxReq=" + maxRequestSize
                    + "|cleanUnix=" + cleanUnix + "|cleanWin=" + cleanWin;
            String exp3 = "mem=3145728|maxFile=41943040|maxReq=52428800|cleanUnix=note.txt|cleanWin=demo.png";
            cases.add(caseJson("upload_thresholds_and_filename_sanitization", "核对 3MB/40MB/50MB 阈值常量与跨平台路径剥离逻辑", exp3, act3));

            // Case 4: Multi-file upload with distinct input names
            String multiBody = "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"fileA\"; filename=\"a.txt\"\r\n"
                    + "Content-Type: text/plain\r\n\r\n"
                    + "alpha\r\n"
                    + "--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"fileB\"; filename=\"b.txt\"\r\n"
                    + "Content-Type: text/plain\r\n\r\n"
                    + "beta-123\r\n"
                    + "--" + boundary + "--\r\n";
            String[] multiResp = postRaw(
                    "http://127.0.0.1:" + port + "/UploadServlet",
                    "multipart/form-data; boundary=" + boundary,
                    multiBody.getBytes(StandardCharsets.UTF_8)
            );
            String act4 = "status=" + multiResp[0] + "|" + multiResp[1];
            String exp4 = "status=200|ok|fields={}|saved=[fileA:a.txt:5, fileB:b.txt:8]";
            cases.add(caseJson("multi_file_multipart_parsing", "验证多个不同 name 的 file 输入项在单次 multipart 请求中分别落盘", exp4, act4));
        } finally {
            server.stop(0);
            deleteRecursively(tempRoot.toFile());
        }

        System.out.println("{");
        System.out.println("  \"version\": \"Eclipse Adoptium OpenJDK " + esc(System.getProperty("java.version")) + "\",");
        System.out.println("  \"cases\": [");
        for (int i = 0; i < cases.size(); i++) {
            System.out.println(cases.get(i) + (i + 1 < cases.size() ? "," : ""));
        }
        System.out.println("  ]");
        System.out.println("}");
    }
}
本例需在 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。

入口文件:projects/servlet-file-uploading-lab/ExploreFileUploading.java

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ExploreFileUploading.java,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Eclipse Adoptium OpenJDK 1.8.0_492 (javac + java) 本地环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Servlet

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1369.zip

下载课程关联工程包:Servlet

课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a1361.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习