How To Upload and Read CSV File On SpringMVC Using OpenCSV

In this function, I use OpenCSV library to help me read csv file. You can read more about OpenCSV on their website.

The form on my jsp:

<form action="${baseURL}/uploadfile" method="POST" enctype="multipart/form-data" >
    <div class="form-group">
        <label>File input</label>
        <input type="file" name="file"/>
    </div>
    <br/><br/>
    <div class="form-group">
        <button type="submit" id="upload">Upload</button>
    </div>
</form>

My controller:

@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public String uploadFile(
        ModelMap model,
        @RequestParam MultipartFile file,
        HttpServletRequest request) {

    if (file.isEmpty()) {
        model.put("msg", "failed to upload file because its empty");
        return "mainpage";
    }

    String rootPath = request.getSession().getServletContext().getRealPath("/");
    File dir = new File(rootPath + File.separator + "uploadedfile");
    if (!dir.exists()) {
        dir.mkdirs();
    }

    File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());

    try {
        try (InputStream is = file.getInputStream();
				BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) {
            int i;
			//write file to server
            while ((i = is.read()) != -1) {
                stream.write(i);
            }
            stream.flush();
        }
    } catch (IOException e) {
        model.put("msg", "failed to process file because : " + e.getMessage());
        return "mainpage";
    }

	String[] nextLine;
    try {
		//read file
		//CSVReader(fileReader, ';', '\'', 1) means
		//using separator ; and using single quote ' . Skip first line when read

        try (FileReader fileReader = new FileReader(serverFile);
			CSVReader reader = new CSVReader(fileReader, ';', '\'', 1);) {
            while ((nextLine = reader.readNext()) != null) {
                System.out.println("content : ");
				for(int i=0;i<nextLine.length;i++){
					System.out.println(nextLine[i]);
				}
			}
		}
    } catch (IOException e) {
        System.out.println("error while reading csv and put to db : " + e.getMessage());
    } 

    model.put("msg", "success upload and process file");
    return "mainpage";
}

One thought on “How To Upload and Read CSV File On SpringMVC Using OpenCSV

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s