2011-11-16 99 views
7

嗨,我想從resteasy服務器返回一個文件。爲此,我在客戶端使用ajax調用rest服務的鏈接。我想在其餘服務中返回文件。我嘗試了這兩個代碼塊,但都沒有按照我想要的那樣工作。從Resteasy服務器返回文件

@POST 
    @Path("/exportContacts") 
    public Response exportContacts(@Context HttpServletRequest request, @QueryParam("alt") String alt) throws IOException { 

      String sb = "Sedat BaSAR"; 
      byte[] outputByte = sb.getBytes(); 


    return Response 
      .ok(outputByte, MediaType.APPLICATION_OCTET_STREAM) 
      .header("content-disposition","attachment; filename = temp.csv") 
      .build(); 
    } 

@POST 
@Path("/exportContacts") 
public Response exportContacts(@Context HttpServletRequest request, @Context HttpServletResponse response, @QueryParam("alt") String alt) throws IOException { 

    response.setContentType("application/octet-stream"); 
    response.setHeader("Content-Disposition", "attachment;filename=temp.csv"); 
    ServletOutputStream out = response.getOutputStream(); 
    try { 

     StringBuilder sb = new StringBuilder("Sedat BaSAR"); 

     InputStream in = 
       new ByteArrayInputStream(sb.toString().getBytes("UTF-8")); 
     byte[] outputByte = sb.getBytes(); 
     //copy binary contect to output stream 
     while (in.read(outputByte, 0, 4096) != -1) { 
      out.write(outputByte, 0, 4096); 
     } 
     in.close(); 
     out.flush(); 
     out.close(); 

    } catch (Exception e) { 
    } 

    return null; 
} 

當我從Firebug控制檯檢查,無論這些代碼塊的響應Ajax調用寫了「塞達特BaSAR」。但是,我想將「Sedat BaSAR」作爲文件返回。我怎樣才能做到這一點?

在此先感謝。

+0

您是否最終找到了解決方案? – rabs

回答

12

有兩種方法可以實現。

1st - 返回一個StreamingOutput實例。

@Produces(MediaType.APPLICATION_OCTET_STREAM) 
public Response download() { 
    InputStream is = getYourInputStream(); 

    StreamingOutput stream = new StreamingOutput() { 

     public void write(OutputStream output) throws IOException, WebApplicationException { 
      try { 
       output.write(IOUtils.toByteArray(is)); 
      } 
      catch (Exception e) { 
       throw new WebApplicationException(e); 
      } 
     } 
}; 

return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition", "attachment; filename=\"temp.csv\"").build(); 
} 

可以返回文件大小增加Content-Length頭,如下面的例子:

return Response.ok(stream, MediaType.APPLICATION_OCTET_STREAM).header("content-disposition", "attachment; filename=\"temp.csv\"").header("Content-Length", getFileSize()).build(); 

但是,如果你不想返回StreamingOutput實例,還有其他的選擇。

2nd - 將輸入流定義爲實體響應。

@Produces(MediaType.APPLICATION_OCTET_STREAM) 
public Response download() { 
    InputStream is = getYourInputStream(); 

    return Response.code(200).entity(is).build(); 
} 
+0

如何返回名稱爲UTF-8的文件? – vanduc1102