LoginSignup
10
2

More than 3 years have passed since last update.

Spring アップロードファイルを読み込んで中身を表示する方法

Last updated at Posted at 2019-06-05

build.gradleでstater-webのところのライブラリを導入しないと必要なクラスがimport出来ないので
はじめに記述する。
書けたらGradleをリフレッシュする。

build.gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile ('org.springframework.boot:spring-boot-starter-web')
}

コントローラーのpostメソッドの引数にMultipartFileクラスのインスタンスを追加する。
これがHTMLから<input type="file">で選んで<input type="submit">で投稿されたファイルの
インスタンスになる。

ModelAndViewController.java
    @RequestMapping(value="/",method=RequestMethod.POST)
    public ModelAndView post(
            @RequestParam("upload_file")MultipartFile uploadFile,
            ModelAndView mav) 
    {
        mav.setViewName("index");
        mav.addObject("file_contents", fileContents(uploadFile));
        mav.addObject("recordSet", list);
        return mav;
    }

読み込んだファイルの中身をテキスト形式に変換して取り出すところ。
MultiPartFileから読み出した時はバイトストリームなのでcsvファイルなどのテキスト形式に変換するにはReader->BufferedReaderと変換していく。(Readerを挟む必要はあるかわからない。)
最終的にはこのコードでいうとbuf変数にファイルの中身がテキスト形式で入っているので後はSwingとかのローカルアプリと同じように読み出すだけ。

ModelAndViewController.java
private List<String> fileContents(MultipartFile uploadFile) {
        List<String> lines = new ArrayList<String>();
        String line = null;
        try {
            InputStream stream = uploadFile.getInputStream();           
            Reader reader = new InputStreamReader(stream);
            BufferedReader buf= new BufferedReader(reader);
            while((line = buf.readLine()) != null) {
                lines.add(line);
            }
            line = buf.readLine();

        } catch (IOException e) {
            line = "Can't read contents.";
            lines.add(line);
            e.printStackTrace();
        }
        return lines;
    }

htmlのformタグにenctype="multipart/form-data"を記述しないとアップロードできない。

index.html
<!-- ファイルのアップロードボタンの実装-->
    <form method="post" action="/" enctype="multipart/form-data">
        <input type="submit" value="ファイルをアップロード">
        <input type="file" name="upload_file">  
    </form>
    <p th:text="${file_name}"></p>
    <table>
<!-- ここから下が結果表示-->
    <tr th:each="line:${file_contents}">
        <td th:text=${line}></td>
    </tr>
    </table>
10
2
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
10
2