如何将八位字节流文件上传到 spring-mvc 应用程序?

Sil*_*sky 4 curl file-upload spring-mvc multipart

通常对于文件上传,我使用了 multipart/form-data 并且效果很好。但现在我的服务器需要能够接受文件 application/octet-stream。

在服务器端我有:

@ResponseBody
@RequestMapping(path = "/mock",
        consumes = { MediaType.APPLICATION_OCTET_STREAM_VALUE },
        method = RequestMethod.POST)
public ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file) {
    return ResponseEntity.accepted().build();
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试用curl 测试它:

curl -v -H "Content-Type:application/octet-stream" \
  --data-binary @/home/user/Desktop/test.txt http://localhost:9090/mock
Run Code Online (Sandbox Code Playgroud)

结果有:

org.springframework.web.multipart.MultipartException: Current request is not a multipart request
Run Code Online (Sandbox Code Playgroud)

我注意到“文件”部分没有在我的curl 命令中指定,但在服务器端是预期的。目前尚不清楚下一步该移动到哪里以及测试命令或服务器或两者都损坏了。

Sve*_*ing 5

由于您没有多部分表单数据消息,因此您无法使用MultipartFile.

你现在有两种可能性。

使用curl 发送多部分消息:(
查看名为 的表单数据file。)

curl -F "file=@/home/user/Desktop/test.txt" http://localhost:9090/mock
Run Code Online (Sandbox Code Playgroud)

或者更改控制器:

@ResponseBody
@RequestMapping(path = "/mock",
        consumes = { MediaType.APPLICATION_OCTET_STREAM_VALUE },
        method = RequestMethod.POST)
public ResponseEntity handleFileUpload(final HttpServletRequest request) {
    // request.getInputStream() will contain the content of the posted file
    return ResponseEntity.accepted().build();
}
Run Code Online (Sandbox Code Playgroud)