Since the necessary classes cannot be imported unless the library at stater-web is installed in build.gradle. Described first. Refresh Gradle when you can write.
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')
}
Add an instance of ** MultipartFile ** class to the argument of the post method of the controller. This is the file that was selected from HTML with \ and posted with \ Become an instance.
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;
}
A place to convert the contents of the read file into text format and extract it. When reading from ** MultiPartFile **, it is a byte stream, so to convert it to a text format such as a csv file, convert it to ** Reader **-> ** BufferedReader **. (I don't know if it is necessary to insert a Reader.) In the end, in this code, the contents of the file are contained in the buf variable in text format, so all you have to do is read it in the same way as a local application such as 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;
}
Uploading is not possible unless ** enctype = "multipart / form-data" ** is described in the html form tag.
index.html
<!--Implementation of file upload button-->
<form method="post" action="/" enctype="multipart/form-data">
<input type="submit" value="Upload file">
<input type="file" name="upload_file">
</form>
<p th:text="${file_name}"></p>
<table>
<!--Below is the result display-->
<tr th:each="line:${file_contents}">
<td th:text=${line}></td>
</tr>
</table>
Recommended Posts