JAX-RSからテキストファイルをダウンロードする

JAX-RSでは、ユーザーがファイルをダウンロードするには、メソッドに `@Produces(" text/plain ")`でアノテーションを付けます:

  1. @Produces( "text/plain") をサービスメソッドに入れ、 Response

戻り値の型。これは、出力がテキストファイルであることを意味します。

  1. ブラウザのポップアップに応答ヘッダに " Content-Disposition "を設定する

ユーザーがダウンロードするためのダウンロードボックス。

JAX-RSでファイルをダウンロードする

JAX-RSでテキストファイルをダウンロードする完全な例を参照してください。

import java.io.File;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

@Path("/file")
public class FileService {

    private static final String FILE__PATH = "c:\\file.log";

    @GET
    @Path("/get")
    @Produces("text/plain")
    public Response getFile() {

        File file = new File(FILE__PATH);

        ResponseBuilder response = Response.ok((Object) file);
        response.header("Content-Disposition",
            "attachment; filename=\"file__from__server.log\"");
        return response.build();

    }

}

デモ

JAX-RSサービスの上に展開し、このURIパターン「 /file/get 」にアクセスします。

Figure:サーバーからのテキストファイル " c:\\ test.log "は、新しいファイル名 " file from server.log "

サーバーからファイルをダウンロードする、title = "download-file-jax-rs"、width = 463、height = 353

ソースコードをダウンロードする

ダウンロード - リンク://wp-content/uploads/2011/07/JAX-RS-Download-TextFile-Example.zip[JAX-RS-Download-TextFile-Example.zip](6 KB)