4
5

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.

SparkとJava8のファイルダウンロードサンプル

Last updated at Posted at 2015-10-16

Spark-Java のファイルダウンロードサンプル。
Servletでの処理そのまま。

起動してhttp://localhost:4567/file にアクセスするとプロジェクトのroot/public/資料.xlsxがダウンロードされる。

DownloadFileSample
package spqrk;

import static spark.Spark.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import spark.utils.IOUtils;

public class HelloWorld {

	public static void main(String[] args) {

		before("/hello", (req, res) -> {
			System.out.println("/helloの前処理");
		});

		get("/hello", (req, res) -> {
			System.out.println("/hello");
			return "Hello Spark World";
		});

		get("/file", (req, res) -> {
			System.out.println("ファイルをダウンロード");

			// ダウンロードファイルの作成
			String fileName = "資料.xlsx";

			// プロジェクトのroot/public/ フォルダが使用される。
			File file = new File("public/" + fileName);
			String savePath = file.getAbsolutePath();

			System.out.println("ダウンロードするファイル=" + savePath);

			byte[] fileContent = null;
			try (InputStream is = new FileInputStream(savePath);) {
				fileContent = IOUtils.toByteArray(is);
			} catch (FileNotFoundException e) {
				throw new RuntimeException(fileName + " not found");
			} catch (IOException e) {
				throw new RuntimeException(e);
			}

			// ファイル名の文字化け対策。
			String downName = URLEncoder.encode(fileName, "UTF-8");

			res.raw().setContentType("application/octet-stream");
			res.raw().setHeader("Content-Disposition", "attachment; filename=" + downName);
			res.raw().setContentLength(fileContent.length);

			try (OutputStream os = res.raw().getOutputStream();) {
				os.write(fileContent);
				os.flush();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}

			return "";
		});

	}
}

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?