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 class="form-group">
        <button type="submit" id="upload">Upload</button>

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()) {

    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 = != -1) {
    } 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++){
    } 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: Logo

You are commenting using your 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