使用Spring WebClient在java中上传文件

V.A*_*wal 3 java upload spring spring-webclient

我正在尝试从普通的 HttpPost 方法迁移到 Spring WebClient,并且我有一个 API 接受两个文件(一个 JSON 和一个 PDF)进行上传。

我尝试发送如下文件,但收到 500 内部服务器错误而不是 200 OK。

String jsonData ="";
ByteArrayOutputStream file;

MultipartBodyBuilder builder = new MultipartBodyBuilder();
String header1 = String.format("form-data; name=%s; filename=%s", "attach", "file.pdf");
String header2 = String.format("form-data; name=%s; filename=%s", "jsonfile", "jsonfile.json");

// This line is causing the problem, Am I making a mistake here?
builder.part("attach", file.toByteArray()).header("Content-Disposition", header1);
// This line works fine.
builder.part("jsonfile", jsonData.getBytes()).header("Content-Disposition", header2);

WebClient webClient = WebClient.create("a url");

        byte[] fileContent = null;
        try {
            fileContent = webClient.post()
                .body(BodyInserters.fromMultipartData(builder.build()))
                .retrieve()
                .onStatus(HttpStatus::isError, res -> handleError(res))
                .bodyToMono(byte[].class)
                .block();
        } catch (Exception e) {
            return null;
        }
Run Code Online (Sandbox Code Playgroud)

但是,如果我不在请求中发送 PDF 文件,则仅使用 JSON 文件即可正常工作。对于邮递员来说,这两种情况都可以正常工作。

我假设我在将 PDF 文件添加到请求时犯了一个错误。尽管文件本身是有效的 PDF,但 API 的响应是 JSON 文件。

如果有人能告诉我这里可能出了什么问题。

V.A*_*wal 6

经过各种更改后,我能够解决这个问题。对于遇到这个问题的人来说可能会很方便。

不要直接使用file.toByteArray(),而是使用 new ByteArrayResource(file.toByteArray())

所以该行看起来像:

builder.part("attach", new ByteArrayResource(file.toByteArray())).header("Content-Disposition", header1);
Run Code Online (Sandbox Code Playgroud)