Upload a file using Java 11 HttpClient to SpringBoot Server

Tags: , ,



My client upload method:

public static void addPhoto(File photo) throws ParseException, IOException, InterruptedException {
    HttpClient client = HttpClient.newBuilder().build();
    HttpRequest request = HttpRequest.newBuilder()
            .header("Content-Type","image/jpg")
            .uri(URI.create(baseUrl + "data/addPhoto?date=4&category=temp&jwt="+jwt))
            .PUT(HttpRequest.BodyPublishers.ofFile(photo.toPath()))
            .build();
    client.send(request, HttpResponse.BodyHandlers.ofString());
}

My Spring Boot method that receives the file:

@PutMapping(path = "/addPhoto")
public @ResponseBody
boolean addPhoto(@RequestParam(name = "jwt") String jwt,
                 @RequestParam("file") MultipartFile file,
                 @RequestParam(name = "date") long date,
                 @RequestParam(name = "category") String category) {
    return crudService.addPhoto(jwt, date, file, category);
}

The current error:

2020-09-17 16:29:02.313 ERROR 8636 --- [nio-5000-exec-9] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause

What kind of headers can I add to ensure my Spring Boot server receives the file without errors?

Answer

MultipartException: Current request is not a multipart request

This is telling you what’s wrong.

In your code: .PUT(HttpRequest.BodyPublishers.ofFile(photo.toPath())), you are doing a PUT request with file’s byte array in BODY. But in your server, you are expecting it as MultipartFile. MultipartFile is a representation of uploaded file with additional data in the POST request body. https://en.wikipedia.org/wiki/MIME#Multipart_messages

You can simply do the following to upload your file:

Ref: https://ganeshtiwaridotcomdotnp.blogspot.com/2020/09/java-httpclient-tutorial-with-file.html

Send filename in request:

.uri(URI.create("http://localhost:8085/addPhoto?fileName=" + photo.getName()))

Receive byte array in RequestBody and fileName in RequestParam

@PostMapping(path = "/addPhoto")
public void addPhoto(@RequestBody byte[] barr,
                     @RequestParam(name = "fileName") String fileName) throws Exception {
    System.out.println(" received file " + fileName + " length " + barr.length);

    try (OutputStream os = new FileOutputStream(new File("UPL" + fileName))) {
        os.write(barr);
    }

}

If you must use MultipartFile then you can do sth similar to:



Source: stackoverflow