You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins 如何在大文件上传场景下发送带额外字段的multipart/form-data请求

大文件multipart/form-data上传附加额外字段的两种实现方案

两种方案都可以避免全量读取大文件到内存,不会触发OutOfMemoryError:

方案1:用FileInputStream构造MultipartRequestEntity

直接绑定本地文件构造输入流,底层会分片读取传输,不需要加载整个文件到内存:

// 绑定大文件路径,仅创建流引用,不读取文件内容
File bigFile = new File("/path/to/large/file");
try (FileInputStream fis = new FileInputStream(bigFile)) {
    // 组合所有请求字段
    Part[] requestParts = {
        // 普通表单字段
        new StringPart("custom_field1", "value1"),
        new StringPart("custom_field2", "value2"),
        // 文件字段,传入流、文件名、MIME类型即可
        new FilePart("upload_file", fis, bigFile.getName(), "application/octet-stream")
    };
    MultipartRequestEntity entity = new MultipartRequestEntity(requestParts, postMethod.getParams());
    postMethod.setRequestEntity(entity);
    // 执行HTTP请求
    httpClient.executeMethod(postMethod);
} catch (IOException e) {
    // 处理异常逻辑
}
  • 上述代码用try-with-resources语法自动管理流关闭,无需手动释放资源

方案2:使用httpRequest uploadFile参数同时附加额外字段

绝大多数httpRequest封装工具原生支持在上传文件接口直接传入额外表单字段,无需手动构造RequestEntity:

Java HttpClient 场景示例

MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
// 添加额外表单字段
entityBuilder.addTextBody("custom_field1", "value1");
entityBuilder.addTextBody("custom_field2", "value2");
// 直接传入文件对象,底层自动用流分片处理
entityBuilder.addBinaryBody("upload_file", new File("/path/to/large/file"), ContentType.DEFAULT_BINARY, "target_file_name");
HttpPost uploadRequest = new HttpPost("https://your-upload-endpoint");
uploadRequest.setEntity(entityBuilder.build());
httpClient.execute(uploadRequest);

前端JavaScript 场景示例

const formData = new FormData();
// 添加额外字段
formData.append('custom_field1', 'value1');
formData.append('custom_field2', 'value2');
// 添加文件对象,不会读取全量内容到内存
formData.append('upload_file', file, 'target_file_name');
// 发起上传请求
fetch('https://your-upload-endpoint', {
  method: 'POST',
  body: formData
});

两种方案的底层实现都采用流式传输,不会将整个文件加载到堆内存,完全适配GB级大文件上传场景

内容的提问来源于stack exchange,提问作者Rob H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 11:45:03