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?

Spring MVCを使ってファイルをダウンロードし、Content-Disposition ヘッダーを処理する

Posted at
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

@RestController
public class MyController {

    @GetMapping("/downloadFile")
    public String downloadFile() throws IOException, InterruptedException {
        // HttpClientのインスタンス作成
        HttpClient client = HttpClient.newHttpClient();

        // GETリクエストの作成
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://example.com/path/to/file"))  // ダウンロード先のURLを指定
            .build();

        // レスポンスをファイルとして保存する
        HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(Paths.get("temp_file")));

        // ステータスコードをチェック
        if (response.statusCode() != 200) {
            return "Failed to download file: HTTP status code " + response.statusCode();
        }

        // Content-Dispositionヘッダーからファイル名を取得
        Optional<String> contentDisposition = response.headers().firstValue("Content-Disposition");
        String fileName = "downloaded_file";
        if (contentDisposition.isPresent() && contentDisposition.get().contains("filename=")) {
            String[] parts = contentDisposition.get().split("filename=");
            if (parts.length > 1) {
                fileName = parts[1].replace("\"", "").trim();
            }
        }

        // ファイルを保存
        Path downloadedFilePath = Paths.get(fileName);
        Files.move(Paths.get("temp_file"), downloadedFilePath);

        return "File downloaded successfully: " + downloadedFilePath.toAbsolutePath();
    }
}
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?