SpringBoot ファイルをダウンロードするサンプル

構文
1.アノテーション@PostMapping(“/パス名")
HTTP POST リクエストを特定のハンドラーメソッドにマッピングするためのアノテーション。

2.インターフェース HttpServletResponse
public interface HttpServletResponse extends ServletResponse

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ServletResponse インターフェースを拡張して、レスポンスを送信する際に HTTP 固有の機能を提供します。
ServletResponse インターフェースを拡張して、レスポンスを送信する際に HTTP 固有の機能を提供します。
ServletResponse インターフェースを拡張して、レスポンスを送信する際に HTTP 固有の機能を提供します。

3.getOutputStream
ServletOutputStream getOutputStream()

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
レスポンスにバイナリデータを書き込むのに適した ServletOutputStream を返します。
サーブレットコンテナーはバイナリデータをエンコードしません。
レスポンスにバイナリデータを書き込むのに適した ServletOutputStream を返します。 サーブレットコンテナーはバイナリデータをエンコードしません。
レスポンスにバイナリデータを書き込むのに適した ServletOutputStream を返します。
サーブレットコンテナーはバイナリデータをエンコードしません。

4.void setContentType(String type)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
レスポンスがまだコミットされていない場合、クライアントに送信されるレスポンスのコンテンツタイプを設定します。
レスポンスがまだコミットされていない場合、クライアントに送信されるレスポンスのコンテンツタイプを設定します。
レスポンスがまだコミットされていない場合、クライアントに送信されるレスポンスのコンテンツタイプを設定します。

操作方法
1.コントローラ側(FileDownloadController.java)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
package com.arkgame.study.demo;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class FileDownloadController {
@GetMapping
String index(Model model) {
return "/index";
}
@PostMapping("/fileDownload")
String download(HttpServletResponse response) {
try (OutputStream os = response.getOutputStream();) {
//ダウンロードファイル
Path filePath = Paths.get("C:/backup/" + "result.pdf");
//バイトに変換
byte[] filebyte = Files.readAllBytes(filePath);
//レスポンスヘッダに値をセット
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=result.pdf");
response.setContentLength(filebyte.length);
os.write(filebyte);
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.arkgame.study.demo; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @Controller public class FileDownloadController { @GetMapping String index(Model model) { return "/index"; } @PostMapping("/fileDownload") String download(HttpServletResponse response) { try (OutputStream os = response.getOutputStream();) { //ダウンロードファイル Path filePath = Paths.get("C:/backup/" + "result.pdf"); //バイトに変換 byte[] filebyte = Files.readAllBytes(filePath); //レスポンスヘッダに値をセット response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=result.pdf"); response.setContentLength(filebyte.length); os.write(filebyte); os.flush(); } catch (IOException e) { e.printStackTrace(); } return null; } }
package com.arkgame.study.demo;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class FileDownloadController {

    @GetMapping
    String index(Model model) {
        return "/index";
    }

    @PostMapping("/fileDownload")
    String download(HttpServletResponse response) {
    	
        try (OutputStream os = response.getOutputStream();) {
            
                //ダウンロードファイル
        	Path filePath = Paths.get("C:/backup/" + "result.pdf");
        	
                  //バイトに変換
            byte[] filebyte = Files.readAllBytes(filePath);
            
                  //レスポンスヘッダに値をセット 
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=result.pdf");
            response.setContentLength(filebyte.length);
            os.write(filebyte);
            os.flush();
                  
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

2.画面(index.html)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html xmlns:th="https://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>ファイルダウンロードサンプル</title>
</head>
<body>
<form method="post" th:action="@{/fileDownload}">
<input type="submit" value="ダウンロード" />
</form>
</body>
</html>
<!DOCTYPE html> <html xmlns:th="https://thymeleaf.org"> <head> <meta charset="UTF-8"> <title>ファイルダウンロードサンプル</title> </head> <body> <form method="post" th:action="@{/fileDownload}"> <input type="submit" value="ダウンロード" /> </form> </body> </html>
<!DOCTYPE html>
<html xmlns:th="https://thymeleaf.org">
<head>
      <meta charset="UTF-8">
      <title>ファイルダウンロードサンプル</title>
</head>
<body>
    <form method="post" th:action="@{/fileDownload}">
      <input type="submit" value="ダウンロード" />
    </form>
</body>
</html>

「ダウンロード」ボタンを押すと、ファイルをダウンロードします。

3.設定ファイル(application.properties)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
server.port = 8768
server.port = 8768
server.port = 8768

ポート番号を変更しています。

Spring Boot

Posted by arkgame