使用Spring Rest同时返回响应并呈现文件以下载到浏览器

时间:2018-11-11 16:00:42

标签: java spring rest spring-mvc

我从我的供应商处收到了一个发布请求,该请求期望即时响应(我正在使用Spring Rest)。我使用此请求来验证一些交易,并允许将文件下载到浏览器上的用户。我的问题是我如何同时将该文件呈现给浏览器以进行下载并将预期的响应返回给供应商。这是我尝试的解决方案(失败)。请帮忙。谢谢。

@RequestMapping(method = {RequestMethod.GET,RequestMethod.POST}, value ="/listeningurl", consumes = "application/xml", produces = "application/xml") 
     public ResponseObject lodgementNotifications(@RequestBody RequesObject reqObject, HttpServletResponse response)
     {

        //do stuffs with reqObject;
        //Generate a fileUrl using some parameters from the reqObject;


                try {
                //copies all bytes from a file to an output stream

                   URL fileURL = new URL(fileUrl); 
                    HttpURLConnection httpConn = (HttpURLConnection) fileURL.openConnection(); 


                       InputStream inputStream = httpConn.getInputStream();

               // set content type 
                   response.setContentType(fileMetaData.getContentType());
               // add response header
                   response.addHeader("Content-Disposition", "attachment; filename=" fileName"));
                   response.setContentLengthLong(fileMetaData.getContentLength());
                   response.setStatus(200);                     

                    FileCopyUtils.copy(inputStream, response.getOutputStream());
                //flushes output stream
                response.getOutputStream().flush();
               } catch (IOException e) {
                System.out.println("Error :- " + e.getMessage());

              }


              // Initialize ResponseObject
              return responseObject

    }

0 个答案:

没有答案