2 回答
TA贡献1794条经验 获得超8个赞
我有示例代码,但在 Kotlin 中。
我希望它能帮助你。
第一种方式(节省内存)
upload(stream: InputStream, filename: string): HashMap<String, Any> {
val request: MultiValueMap<String, Any> = LinkedMultiValueMap();
request.set("file", MultipartInputStreamFileResource(stream, filename))
return client.post().uri("http://localhost:8080/files")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(request))
.awaitExchange().awaitBody()
}
class MultipartInputStreamFileResource(inputStream: InputStream?, private val filename: String) : InputStreamResource(inputStream!!) {
override fun getFilename(): String? {
return filename
}
@Throws(IOException::class)
override fun contentLength(): Long {
return -1 // we do not want to generally read the whole stream into memory ...
}
}
第二种方式
//You wrote a file to somewhere in the controller then send the file through webclient
upload(stream: InputStream, filename: string): HashMap<String, Any> {
val request: MultiValueMap<String, Any> = LinkedMultiValueMap();
request.set("file", FileSystemResource(File("/tmp/file.jpg")))
return client.post().uri("http://localhost:8080/files")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(request))
.awaitExchange().awaitBody()
}
第三种方式
upload(file: Part): HashMap<String, Any> {
val request: MultiValueMap<String, Any> = LinkedMultiValueMap();
request.set("file", file)
return client.post().uri("http://localhost:8080/files")
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(BodyInserters.fromMultipartData(request))
.awaitExchange().awaitBody()
}
TA贡献1826条经验 获得超6个赞
这对我有用
MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
bodyBuilder.part("file", new ClassPathResource("/bulk_upload/test.xlsx"));
List<DataFileAdjustment> list = webClient.post().uri("/bulk").accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromMultipartData(bodyBuilder.build()))
.exchange()
.expectStatus().isOk()
添加回答
举报