2012-08-30 2 views
1

나는 봄을 사용하여 REST webserivce를 쓰고있다. 나는 응답에서 파일을 돌려 보내야한다.REST 기반 웹 서비스에서 자바를 사용하여

GET 호출과 사용자가 URL을 입력하면 브라우저에 다운로드 섹션이 표시되어야합니다.

컨트롤러에서 반환 유형이 무엇인지 잘 모르겠습니다. 모든 콘텐츠 유형 i 코드를 지정해야합니까?

답변

0

사용자가 원하는 모든 이름을 가질 수있는 컨트롤러 메소드는로드하려는보기에 대해 정의 된 views.xml에 정의 된 URL 이름을 가진 String을 리턴합니다.이 경우 다운로드 섹션. 그래서 컨트롤러는 다음과 같습니다

@Controller 
public class MyController { 

    @RequestMapping(value = "/downloads", method = RequestMethod.GET) 
    public String getDownloadSection() { 
     System.out.println("getting downloads"); 
     return "downloads/index"; 
    } 
} 

귀하의 views.xml 태그를 포함해야합니다

<definition extends="default" name="downloads/index"> 
<put-attribute name="body" value="/WEB-INF/views/downloads/index.jspx"/> 
</definition> 

는 = "기본"이 레이아웃에 있어야 타일 정의입니다 확장합니다. xml

나는 그것에 대해 그렇게 생각한다. // yoursite/downloads에 GET 요청을하면 메시지를 인쇄해야합니다. 귀하의 질문에 대답해야

은 내가

+0

감사합니다 도움이되기를 바랍니다의 아래 부분을 사용했다. 나는 이것도 시도 할 것이다 :) – user1332962

4

또 하나 개의 스레드에서 발견 된

FileInputStream inputStream = new FileInputStream("FileInputStreamDemo.java"); //read the file 

    response.setHeader("Content-Disposition","attachment; filename=test.txt"); 
    try { 
     int c; 
     while ((c = inputStream.read()) != -1) { 
     response.getWriter().write(c); 
     } 
    } finally { 
     if (inputStream != null) 
      inputStream.close(); 
      response.getWriter().close(); 
    } 

코드의 아래 부분을 사용 희망 내 프로젝트에서 비슷한 요구 사항. 나는 코드

@Controller 
@RequestMapping("/reports") 
public class ReportsController { 

    protected static String PRODUCTIVITY_REPORT_FILE = "productivityReportFile"; 

    @Resource(name="propertyMap") 
    protected Map<String, String> propertyMap; 

    @RequestMapping(value="/cratl/productivity_report", method=RequestMethod.GET, produces="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") 
    public @ResponseBody byte[] getProductivityReport() 
      throws Exception { 
     byte[] reportBytes = null; 
     try { 
      File reportFile = new File(propertyMap.get(PRODUCTIVITY_REPORT_FILE)); 
      if (reportFile != null && reportFile.exists()) { 
       InputStream reportInputStream = new FileInputStream(reportFile); 
       long length = reportFile.length(); 
       reportBytes = new byte[(int)length]; 
       int offset = 0; 
       int numRead = 0; 
       while (offset < reportBytes.length 
         && (numRead = reportInputStream.read(reportBytes, offset, reportBytes.length-offset)) >= 0) { 
        offset += numRead; 
       } 
       if (offset < reportBytes.length) { 
        throw new Exception("Could not completely read file "+ reportFile.getName()); 
       } 
       reportInputStream.close(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return reportBytes; 
    } 

내가 당신에게 당신의 도움에 대한

+0

사람이 왜이 하나가 -1로 득점하는지 설명 할 수 있을까? –

관련 문제