简体   繁体   English

在 Spring 引导 rest Z594C103F2C6E31EC01D1Z 中的 stream 中访问多部分/表单数据中的文件

[英]Access File in multipart/form-data in a stream like fashion in Spring Boot rest controller

following scenario: Service A receives a multipart/form-data request and needs to forward it to Service B. Because the file in the request can be of arbitrary size, Service A needs to stream the file to Service B as soon as possible.如下场景:服务A收到一个multipart/form-data请求,需要转发给服务B。由于请求中的文件可以是任意大小,服务A需要尽快将文件stream发送给服务B。 At the moment Service A can receive the requests but Spring Boot will load the whole request/file into memory resulting in a really high memory footprint.目前服务 A 可以接收请求,但 Spring 引导会将整个请求/文件加载到 memory 中,从而导致非常高的 memory 占用空间。 I also tried the often suggested apache commons-fileupload package but without the expected result.我还尝试了经常建议的 apache commons-fileupload package 但没有预期的结果。

This leads me to the following question:这导致我提出以下问题:

Is it even possible in spring boot to access the incomming http request in a stream like manner without loading the whole thing into the memory or a file? Is it even possible in spring boot to access the incomming http request in a stream like manner without loading the whole thing into the memory or a file?

Thank you!谢谢!

Unfortunately, I don't think it's possible to receive a value without loading it into either memory or onto a temporary location on the disk .不幸的是,我认为如果不将值加载到 memory 或磁盘上的临时位置,就不可能接收到值。

If you look at the configuration, the value spring.servlet.multipart.file-size-threshold=2KB defines at what point Spring should stop loading objects into memory, and instead start writing them to the disk.如果您查看配置,值spring.servlet.multipart.file-size-threshold=2KB定义了 Spring 应该在什么时候停止将对象加载到 ZCD69B4957F06CD818D7ZBF3D61980E2 并开始将它们写入磁盘。

If you still want to use a stream, it's easily done by accepting a MultipartFile and calling "getInputStream()"如果您仍想使用 stream,可以通过接受 MultipartFile 并调用“getInputStream()”轻松完成

@PostMapping
public void yourRequest(@RequestParam("file") MultipartFile file) {
    InputStream inputStream = file.getInputStream();

    // your code
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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