2011-10-04 6 views
8

저는 RESTful 웹 서비스를 만들기 위해 CXF와 Spring을 사용하는 것이 새로운 방법입니다.RESTful은 이진 파일을 생성합니다.

이것은 내 문제입니다 : "모든"종류의 파일 (이미지, 문서, TXT 또는 PDF 일 수 있음) 및 XML을 생성하는 서비스를 만들고 싶습니다. 지금까지이 코드를 얻었습니다 :

@Path("/download/") 
@GET 
@Produces({"application/*"}) 
public CustomXML getFile() throws Exception; 

어디서부터 시작해야 할 지 잘 모르겠습니다.

편집 : 브라이언트 눅의

전체 코드 (감사합니다!)

@Path("/download/") 
@GET 
public javax.ws.rs.core.Response getFile() throws Exception { 
    if (/* want the pdf file */) { 
     File file = new File("..."); 
     return Response.ok(file, MediaType.APPLICATION_OCTET_STREAM) 
      .header("content-disposition", "attachment; filename =" + file.getName()) 
      .build(); 
    } 

    /* default to xml file */ 
    return Response.ok(new FileInputStream("custom.xml")).type("application/xml").build(); 
} 
+0

문제가 무엇인지 설명하여 시작해보십시오. 지금까지는 코드를 실행했을 때 일어나는 일, 발생한 오류 등을 언급하지 않았습니다. –

+0

프레임 워크가'getFile() '/ download'에서 요청할 때마다 요청한 파일을 생성 할 수 있습니까? 이 경우 getFile()의 구현이 어떻게 실제로 요청되었는지를 알 수있는 방법이다. – Wyzard

+0

@Wyzard 예, 구현 및 주석 유형을 많이 요구하지 않기를 바랍니다. –

답변

15

는 모든 파일을 반환 할 경우, 당신은 당신의 방법보다 "일반적인"확인하고 javax.ws를 반환 할 수 있습니다 프로그래밍 Content-Type 헤더를 설정할 수 있습니다 .rs.core.Response :

@Path("/download/") 
@GET 
public javax.ws.rs.core.Response getFile() throws Exception { 
    if (/* want the pdf file */) { 
     return Response.ok(new File(/*...*/)).type("application/pdf").build(); 
    } 

    /* default to xml file */ 
    return Response.ok(new FileInputStream("custom.xml")).type("application/xml").build(); 
} 
0

우리는 또한 CXF와 스프링을 사용하고, 이쪽은 내 것이 바람직 API입니다.

import javax.ws.rs.core.Context; 

@Path("/") 
public interface ContentService 
{ 
    @GET 
    @Path("/download/") 
    @Produces(MediaType.WILDCARD) 
    InputStream getFile() throws Exception; 
} 

@Component 
public class ContentServiceImpl implements ContentService 
{ 
    @Context 
    private MessageContext context; 

    @Override 
    public InputStream getFile() throws Exception 
    { 
     File f; 
     String contentType; 
     if (/* want the pdf file */) { 
      f = new File("...pdf"); 
      contentType = MediaType.APPLICATION_PDF_VALUE; 
     } else { /* default to xml file */ 
      f = new File("custom.xml"); 
      contentType = MediaType.APPLICATION_XML_VALUE; 
     } 
     context.getHttpServletResponse().setContentType(contentType); 
     context.getHttpServletResponse().setHeader("Content-Disposition", "attachment; filename=" + f.getName()); 
     return new FileInputStream(f); 
    } 
} 
관련 문제