春天的上传文件读取和显示内容的方法

如果在build.gradle中不引入stater-web的库,就无法导入所需的类,所以需要首先进行描述。
完成后刷新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中通过选择并通过提交的文件的实例。

    @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等本地应用程序一样仅读取即可。

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的

标签中添加enctype=”multipart/form-data”,就无法上传文件。

<!-- ファイルのアップロードボタンの実装-->
    <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>