使用Java 11 HttpClient将文件上传到SpringBoot服务器。

huangapple go评论80阅读模式
英文:

Upload a file using Java 11 HttpClient to SpringBoot Server

问题

我的客户端上传方法:

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());
}

我的Spring Boot接收文件的方法:

@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);
}

当前的错误:

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

我应该添加什么样的标头以确保我的Spring Boot服务器可以无错误地接收文件?

英文:

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?

答案1

得分: 3

MultipartException: Current request is not a multipart request

这是在告诉你出了什么问题。

在你的代码中:.PUT(HttpRequest.BodyPublishers.ofFile(photo.toPath())),你正在进行一个带有文件字节数组的PUT请求,将其放在了请求体中。但是在你的服务器端,你却期望它是一个MultipartFile(多部分文件)。MultipartFile是一个在POST请求体中附带额外数据的上传文件表示。https://en.wikipedia.org/wiki/MIME#Multipart_messages

你可以简单地按照以下方式上传你的文件:

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

在请求中发送文件名:

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

在RequestBody中接收字节数组,并在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);
    }
}

如果你必须使用MultipartFile,那么你可以类似于以下方式处理:

英文:

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:

huangapple
  • 本文由 发表于 2020年9月18日 07:30:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63947359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定