通过REST Web服务ResponseEntity <byte []>接收文件流

时间:2015-12-14 13:23:03

标签: java matlab file rest stream

我写了一个方法,通过rest web服务将文件作为字节数组发送,在客户端我希望以流的形式接收这个文件(客户端是一个使用java代码的matlab应用程序)。 当我发送文件超过300MB时,我在matlab上收到堆错误,因为堆内存设置在356MB而不是eclipse是1024MB。是否可以使用流接收ResponseEntity,以便一次存储每个字节?或者我必须在1024上增加Matlab堆内存?我在服务器上有这个代码:

@Override
@RequestMapping(value = "/file", method = RequestMethod.GET) 
public  ResponseEntity<byte[]> getAcquisition(HttpServletResponse resp,@RequestParam(value="filePath", required = true) String filePath){
    final HttpHeaders headers = new HttpHeaders();
    OutputStream outputStream = null;
    File toServeUp= null;
    try{
        toServeUp=new File(filePath);
        if (!toServeUp.exists()){
            headers.setContentType(MediaType.TEXT_PLAIN);
            LOG.error("Threw exception in MatlabClientControllerImpl::getAcquisition : File doesn't exists!!");
            String message = "ERROR: Could not retrieve file on server, check the path!";       
            return new ResponseEntity<byte[]>(message.getBytes(Charset.forName("UTF-8")), headers, HttpStatus.OK);
        }else{
            try(InputStream inputStream = new FileInputStream(toServeUp);) {
                resp.setContentType("application/octet-stream"); 
                resp.setHeader("Content-Disposition", "attachment; filename=\""+toServeUp.getName()+"\"");
                Long fileSize = toServeUp.length();
                resp.setContentLength(fileSize.intValue());
                outputStream = resp.getOutputStream();
                byte[] buffer = new byte[1024];
                int read = 0;
                while ((read = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, read);
                }
                headers.setContentType(MediaType.TEXT_PLAIN);
                return new ResponseEntity<byte[]>("ok".getBytes(), headers, HttpStatus.OK);
            }
            catch (Exception e) {
                headers.setContentType(MediaType.TEXT_PLAIN);
                ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
                LOG.error("Threw exception in MatlabClientControllerImpl::getAcquisition :" + errorResponse.getStacktrace());
                String message = "ERROR: Could not send file!";     
                return new ResponseEntity<byte[]>(message.getBytes(("UTF-8")), headers, HttpStatus.OK);
            }finally{
                //close the streams to prevent memory leaks
                try {
                    if (outputStream!=null){
                        outputStream.flush();
                        outputStream.close();           
                    }
                } catch (IOException e) {
                    headers.setContentType(MediaType.TEXT_PLAIN);
                    ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
                    LOG.error("Threw exception in MatlabClientControllerImpl::getAcquisition :" + errorResponse.getStacktrace());
                    String message = "ERROR: Could not close stream.!";     
                    return new ResponseEntity<byte[]>(message.getBytes("UTF-8"), headers, HttpStatus.OK);
                }
            }   
        }
    }catch(Exception e){
        headers.setContentType(MediaType.TEXT_PLAIN);
        ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
        LOG.error("Threw exception in MatlabClientControllerImpl::getAcquisition :" + errorResponse.getStacktrace());
        String message = "ERROR: Error in the path, check it!";     
        return new ResponseEntity<byte[]>(message.getBytes(), headers, HttpStatus.OK);
    }
}

在客户端我有:

@Override
    public Response getFile(String serverIp, String toStorePath, String filePath){
        ResponseEntity<byte[]> responseEntity = null;
        try{
            RestTemplate restTemplate = new RestTemplate();
            responseEntity  = restTemplate.getForEntity(serverIp + "ATS/client/file/?filePath={filePath}", byte[].class, filePath); 

            if (MediaType.TEXT_PLAIN.toString().equals(responseEntity.getHeaders().getContentType().toString()))
                return new Response(false, false, new String(responseEntity.getBody(),Charset.forName("UTF-8")), null);
            else{
                Path p = Paths.get(filePath);
                String fileName = p.getFileName().toString();
                FileOutputStream fos = new FileOutputStream(toStorePath+"\\"+ fileName);
                fos.write(responseEntity.getBody());
                fos.close();
                return new Response(true, true, "Your file has been downloaded!", null);
            }
        }catch(Exception e){
            ErrorResponse errorResponse= ErrorResponseBuilder.buildErrorResponse(e);
            return new Response(false, false, "Error on the client side!" , errorResponse);
        }
    }

实际上,所有文件都在responseEntity中,并且它会抛出堆异常。 谢谢,最好的问候

1 个答案:

答案 0 :(得分:0)

你可以使用setBufferRequestBody(false)生成一个StreamingClientHttpRequest,它在调用getBody()时打开连接。

final RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);     
restTemplate.setRequestFactory(requestFactory);

之后,我认为使用FileSystemResource作为您的请求主体将做正确的事。