0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JAX-RSを使って動画ファイルをダウンロードする

Posted at

動画のダウンロードで苦労したので実装メモを残しておきます。

基本的に動画ファイルはサイズが大きいため、ブラウザで再生するまでに時間がかかるので、
分割してダウンロードする方法で行いました。

実装サンプル

@GET
@Path("video")
@Produces("video/mp4")
public Response getVideo(){

    InputStream is = new FileInputStream("ファイルパス");
    int bufferSize = 300 * 1024;

    // リクエストヘッダのRangeの内容を取得する。
    String range = this.request.getHeader("Range");

    // rangeの内容から bytes=100-200 => [0]=100,[1]=200
    String rangeValue[] = range.substring(range.indexOf("=") + 1).split("-");

    // ファイルサイズを取得
    int fileSize = is.available();

    // 開始サイズを取得
    int start = Integer.parseInt(rangeValue[0]);

    // 終了サイズを取得()
    int end = rangeValue.length < 2 ? fileSize - 1 : Integer.parseInt(rangeValue[1]);

    // レスポンスのコンテンツサイズを取得
    int contentLength = end - start + 1;

    if (contentLength > bufferSize) {
        // コンテンツサイズがバッファサイズを超えた場合
        contentLength = bufferSize;
        end = contentLength + start - 1;
    }

    // InputStreamからbyte配列を取得
    byte[] buf = new byte[fileSize];
    while (is.read(buf) != -1) {
    }

    return Response.ok(new ByteArrayInputStream(buf, start, contentLength))
           .status(Response.Status.PARTIAL_CONTENT)
           .header("Content-Disposition", "inline")
           .header("Content-Range", MessageFormat.format("bytes {0}-{1}/{2}", String.valueOf(start),String.valueOf(end),String.valueOf(fileSize)))
           .header("Content-Length", contentLength)
           .build();
}

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?