【问题标题】:How can I convert FilePart to byte[] in Spring 5 MVC如何在 Spring 5 MVC 中将 FilePart 转换为 byte[]
【发布时间】:2020-06-09 08:44:25
【问题描述】:

我有控制器方法,可以从网络表单接收和上传文件。如何从 FilePart 中提取字节数组并将其保存到 DB?

我可以通过使用 FilePart.transferTo() 将 FilePart 保存到文件中来做到这一点,但这看起来很慢而且很难看。有更好的方法吗?

import org.springframework.http.codec.multipart.FilePart;
import org.springframework.web.bind.annotation.*;


 Mono<UploadResult> uploadFile(@RequestParam("files") FilePart file){

    byte[] fileAsByteArray = convertFilePartToByteArray(file);

    fileService.saveByteArrayToDB(fileAsByteArray);

    /* Rest of the method */
 }

【问题讨论】:

    标签: java spring spring-mvc project-reactor reactor


    【解决方案1】:

    您可以利用内部的dataBuffer 并将它们转换为byte[]

    辅助函数:

    suspend fun FilePart.toBytes(): ByteArray {
        val bytesList: List<ByteArray> = this.content()
                .flatMap { dataBuffer -> Flux.just(dataBuffer.asByteBuffer().array()) }
                .collectList()
                .awaitFirst()
    
        // concat ByteArrays
        val byteStream = ByteArrayOutputStream()
        bytesList.forEach { bytes -> byteStream.write(bytes) }
        return byteStream.toByteArray()
    }
    

    控制器:

    @PostMapping("/upload", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
    suspend fun upload(@RequestPart("file") file: Mono<FilePart>) {
        val bytes = file.awaitFirst().toBytes()
        myService.handle(bytes) // do your business stuff
    }
    

    【讨论】:

      【解决方案2】:

      另一种方法是在控制器中接收org.springframework.web.multipartMultipartFile。您的请求必须是 multipart/form-data 并且您可以在 @RequestPart 注释中按名称获取这些文件。

      @RequestPart("file") MultipartFile file

      获取MultipartFile的byte[]很简单,使用file.getBytes()即可。

      【讨论】:

      • MultipartFile 不适用于 Spring Webflux
      • 此答案一般不起作用,也不会响应答案,因为 Webflux 使用 Flux&lt;Part&gt; 作为正文而不是 Multipart
      【解决方案3】:

      你可以这样做:

      file.content()
      .map { it -> it.asInputStream().readAllBytes() }
      .map { it -> fileService.saveByteArrayToDB(it) } // it is Byte array
      

      【讨论】:

        【解决方案4】:

        你是说接口org.springframework.http.codec.multipart.FilePart吗?

        How to correctly read Flux<DataBuffer> and convert it to a single inputStream

        【讨论】:

        • 很公平,我添加了一些导入以使上下文更加清晰。无论如何,您正确地读懂了我的想法:)但是 file.content().asByteBuffer() 不起作用,因为文件的类型是 Flux
        猜你喜欢
        • 1970-01-01
        • 2021-09-05
        • 2020-02-27
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多