我是 Spring 的 WebClient 的新手。我正在嘗試使用內容型別應用程式/八位位元組流發布檔案的內容。最初我將檔案的內容加載到一個位元組陣列中并使用 .bodyValue() 添加它。這完美地作業。
byte[] data;
// read file into byte array here ...
FileUploadResponse resp = client.post().uri(uri)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.accept(MediaType.APPLICATION_JSON)
.bodyValue(data) // From byte[]
.retrieve()
.bodyToMono(FileUploadResponse.class)
.block();
顯然將檔案的全部內容加載到記憶體中并不是很好。所以我做了一些搜索,看起來我需要使用“來自資源正文插入器”。所以我把代碼改成這樣:
// Use a Spring FileSystemResource that will be used to insert the data into the body.
FileSystemResource resource = new FileSystemResource(localFilename);
// Create a web client
WebClient client = WebClient.create();
FileUploadResponse resp = client.post().uri(uri)
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromResource(resource)) // From file resource
.retrieve()
.bodyToMono(FileUploadResponse.class)
.block();
現在內容型別作為“文本/純文本”發送(見下文)
POST /fileupload
accept-encoding: gzip
user-agent: ReactorNetty/0.9.11.RELEASE
host: localhost:8080
Content-Type: text/plain
Accept: application/json
我究竟做錯了什么?BodyInserters.fromResource() 是否總是將內容型別覆寫為“文本/純文本”?還有其他方法我應該這樣做嗎?
謝謝!
uj5u.com熱心網友回復:
這是由于對 in 的特定處理而發生的。它嘗試通過檔案擴展名檢測 mime 型別。application/octet-streamResourceHttpMessageWriter
您可以InputStreamResource改為使用application/octet-stream
var resource = new InputStreamResource(new FileInputStream(localFilename));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441883.html
上一篇:如何創建一個以json格式提取資料并將其存盤在csv檔案中的回圈?
下一篇:SpringFramework升級5.X導致org.springframework.context.SmartLifecycle的錯誤類檔案未找到
