简体   繁体   中英

Using Spring WebClient to upload a file in java

I am trying to migrate from normal HttpPost methods to Spring WebClient and I have an API that accepts two files (one JSON and one PDF) for upload.

I am trying to send the files like below, but getting a 500 Internal Server Error instead of the 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;
        }

However, If I do not send the PDF file in the request, it works fine with only the JSON file. With the Postman both cases work fine.

I assume that I am making a mistake when adding the PDF file to the request. Though the file itself is a valid PDF, and the response of the API is a JSON file.

If someone could tell me what could possibly be wrong here.

After various changes, I was able to fix this issue. It might come handy for someone who stumbles into this issue.

Instead of using file.toByteArray() directly, use new ByteArrayResource(file.toByteArray()) instead.

So the line looks like:

builder.part("attach", new ByteArrayResource(file.toByteArray())).header("Content-Disposition", header1);

Maybe if you put "file.pdf" in line 5 into quotes solve your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM