我正在尝试用Java上传文件。
我的块上传功能:
@Async
private Future<String> sendChunk(byte[] chunk, int start, int end, int numberOfChunks, String name, String sessionId) throws IOException {
LinkedMultiValueMap<String, Object> requestParams = new LinkedMultiValueMap<>();
requestParams.add("data", new String(java.util.Base64.getEncoder().encode(chunk), "UTF-8"));
requestParams.add("start", start);
requestParams.add("end", end);
requestParams.add("numberOfChunks", numberOfChunks);
requestParams.add("fileName", name);
requestParams.add("session", sessionId);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(requestParams);
UploadResponse uploadResponse = restTemplate.exchange(fileServiceUrl, HttpMethod.POST, requestEntity, new ParameterizedTypeReference<UploadResponse>(){}).getBody();
return new AsyncResult<>(uploadResponse.getSessionId());
}
这就是File-Service-API的样子:
@RequestMapping(value = "/simpleUploader", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<UploadResponse> simpleUploader(
@RequestParam("data") String data,
@RequestParam("session") String sessionId,
@RequestParam("start") int start,
@RequestParam("end") int end,
@RequestParam("numberOfChunks") int numberOfChunks,
@RequestParam("fileName") String fileName) throws IOException {
....
}
现在,如果我尝试上传一个Chunk,文件服务会以400 - Bad Request
回复
Stack-Trace:
org.springframework.web.client.HttpClientErrorException:400 null at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91) 在org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667) 在org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620) 在org.springframework.web.client.RestTemplate.execute(RestTemplate.java:580) 在org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:526)
即使在它进入API函数之前,它也会被Spring拒绝 我已经以相同的方式上传,但在Javascript中。从Javascript开始,一切正常 我错过了什么?
答案 0 :(得分:0)
我的代码唯一的问题是,#34; sessionId&#34;我第一次调用文件服务API时将null
当我将Map Entry的值设置为null时,整个Entry不会被传递。我不知道。
我的修复是向defaultValue
添加@RequestParam("session") String sessionId
,以便方法声明如下:
@RequestMapping(value = "/simpleUploader", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<UploadResponse> simpleUploader(
...
@RequestParam(value = "session", defaultValue = "") String sessionId,
... ) throws IOException {
....
}
答案 1 :(得分:0)
@Async有两个限制。
http://www.baeldung.com/spring-async
尝试将private
更改为public
@Async
public Future<String> sendChunk(byte[] chunk, int start, int end, int numberOfChunks, String name, String sessionId) throws IOException {