2
1

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 1 year has passed since last update.

SpringBoot でファイルダウンロード

Last updated at Posted at 2023-11-01

SpringBootにて、ファイルをダウンロードするユーティリティメソッドを作ったのでメモとして残します。
引数は、ダウンロード対象のファイルパス、出力ファイル名、HttpServletResponseです。
Controllerの引数でHttpServletResponseを読み込むことで、これを利用することができます。


	/**
	 * ファイルダウンロード
	 * 
	 * @param originFilePath ダウンロードファイルパス
	 * @param outputFileName 出力ファイル名
	 * @param response       HttpServletResponse
	 */
	public static void downloadFile(String originFilePath, String outputFileName, HttpServletResponse response) {
		String CONTENT_DISPOSITION_FORMAT = "attachment; filename=\"%s\"; filename*=UTF-8''%s";
		outputFileName = String.format(CONTENT_DISPOSITION_FORMAT, outputFileName,
				UriUtils.encode(outputFileName, StandardCharsets.UTF_8.name()));
		try (OutputStream os = response.getOutputStream();) {
			Path filePath = Path.of(originFilePath);
			byte[] fb = Files.readAllBytes(filePath);
			response.setContentType("application/octet-stream");
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, outputFileName);
			response.setContentLength(fb.length);
			os.write(fb);
			os.flush();
			Files.delete(filePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?