文件上传Java Spring

时间:2017-04-13 07:51:52

标签: java spring

我正在尝试用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开始,一切正常 我错过了什么?

2 个答案:

答案 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 {