2017-07-09 10 views
0

jersey apiを使用してデータベースからpdf(BLOBとして保存)を取得したい 私はmybatisをデータベースフレームワークとして使用しています。 私はpdfをダウンロードすることができますが、問題は私がファイルとして保存し、それを応答で渡すデータベースとして入力ストリームを取得しますが、私はサーバーにそのファイルを保存したくない、私は直接ファイルが欲しいですユーザーにダウンロードされます。サーバに保存せずにデータベースからファイルをダウンロード

現在のプロセス:

DATABASE ------->入力ストリーム----->ファイル----------->応答に追加-----

DATABASE ---------->入力ストリームは------------>に追加します。それは

  retrieving  making file passing file   user downloads 

私が欲しいもの>ユーザーのダウンロードレスポンス------->ユーザーがダウンロードします

  retrieving   passing file    user downloads 

私はデータは、リソース・インターフェース

@GET 
@Path("v1/download/{id}") 
@Produces(MediaType.APPLICATION_OCTET_STREAM) 
public Response downloadFile(@PathParam("id") int id) throws IOException, SQLException; 

リソースのImpl

@Override 
public Response downloadFile(int id) throws IOException, SQLException { 
    // TODO Auto-generated method stub 
    File file = fileUploadService.downloadFile(id); 

    ResponseBuilder response = Response.ok(file); 
    response.header("Content-Disposition", "attachment;filename=aman.pdf"); 
    return response.build(); 
} 

サービスメソッド

@Override 
public File downloadFile(int id) throws IOException { 
    // TODO Auto-generated method stub 
    File fil=new File("src/main/resources/Sample.pdf"); 
    FileUploadModel fm =mapper.downloadFile(id); 
    InputStream inputStream = fm.getDaFile(); 
    outputStream = new FileOutputStream(fil); 
    int read = 0; 
    byte[] bytes = new byte[102400000]; 

    while ((read = inputStream.read(bytes)) != -1) { 
     outputStream.write(bytes, 0, read); 
    } 
    return fil; 
} 

このC

機密であるとして、サーバで行うのファイルを削除したいですodeは動作していますが、サーバー側のファイルを削除したい、つまり削除したいファイル ファイルfil = new File( "src/main/resources/Sample.pdf")、この操作はサービスメソッドです。

ありがとうございます。

答えて

2

Fileを使用する代わりに、ByteArrayOutputStreamを使用して書き込みます。結果をbyte []として返し、Response.ok(コンテンツ)に渡すことができます。

はこれをテストしていないが、このような何か:

public byte[] downloadFile(int id) throws IOException { 
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    FileUploadModel fm =mapper.downloadFile(id); 
    InputStream inputStream = fm.getDaFile(); 
    int read = 0; 
    byte[] bytes = new byte[1024]; 

    while ((read = inputStream.read(bytes)) != -1) { 
     out.write(bytes, 0, read); 
    } 
    return out.toByteArray(); 
} 

また、それは、アレイに割り当てるバイトがたくさんあります。あなたは何が効果的か試してみることができますが、1024のようなもので十分でしょう。

Content-Typeの応答に別のヘッダーを追加することもできます。

+0

効果があります。どうもありがとう 。 – Aman

関連する問題