2011-11-16 9 views
7

こんにちは、私はresteasyサーバーからファイルを返送したかったのです。この目的のために、私はajaxで休憩サービスを呼び出すクライアント側のリンクを持っています。私は残りのサービスでファイルを返すしたいです。私はこれら2つのコードブロックを試しましたが、両方とも私が望んでいたように動作しませんでした。Resteasy Serverからの返信ファイル

@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; 
} 

は、コードのこれらのブロックの両方は、AJAX呼び出しに応じて、「Sedat BaSAR」を書きました。しかし、 "Sedat BaSAR"をファイルとして返したいと思います。どうやってやるの?

ありがとうございます。

+0

あなたはこの解決策を見つけることになりましたか? – rabs

答えて

12

2つの方法があります。

1st - StreamingOutput instaceを返します。

@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

関連する問題