How to Upload CSV Files using Apache FileUpload/CSV

This article represents code samples on how to use Apache Commons FileUpload and Apache Commons CSV libraries to upload CSV file using Java Servlet. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.


Code Samples – Java Code

Following is the code for Java Servlet.

package com.vitalflux.core;

import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileIOController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (ServletFileUpload.isMultipartContent(request)) {
			try {
				List multiparts = new ServletFileUpload(
						new DiskFileItemFactory()).parseRequest(request);
				for (FileItem item : multiparts) {
					// If the item is a string content
					if (!item.isFormField()) {
						String content = item.getString();
						StringReader sReader = new StringReader(content);
						// Reads the file with headers as First Name and Last Name
						Iterable records = CSVFormat.RFC4180
						// Iterate over different rows
						for (CSVRecord record : records) {
							String lastName = record.get("Last Name");
							String firstName = record.get("First Name");
							System.out.println("First Name: " + firstName
									+ ", Last Name: " + lastName);
				// File uploaded successfully
				request.setAttribute("message", "File Uploaded Successfully");
			} catch (Exception ex) {
				request.setAttribute("message", "File Upload Failed due to "
						+ ex);
		} else {
					"Sorry this Servlet only handles file upload request");
		// Redirects the response to JSP page
		RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( "/WEB-INF/views/upload.jsp" );
		dispatcher.forward(request, response);

Code Samples – Web.xml

Following is the code which one would want to define in web.xml. This defines configuration for above given servlet.



Code Samples – UI Code

Following is the UI code. Note down the enctype=”multipart/form-data” within Form tag.

<!DOCTYPE html>
<title>Upload File</title>
<!-- Mobile Specific Meta -->	
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<!--[if IE]><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'><![endif]-->

    <!-- Bootstrap -->
    <link href="/assets/css/bootstrap.css" rel="stylesheet">
<body class="container">
<h1>Upload the file</h1>
<form action="/vitalflux/uploadfile" method="post"  enctype="multipart/form-data">
          <div class="form-group">
            <label for="file" class="control-label">File</label>
            <input type="file" class="form-control" name="file" id="file" placeholder="Select a file" required>
          <div class="modal-footer">			          	
	        <button ng-if="showSubmit" class="btn btn-primary" type="submit">Submit</button>
<script src="/assets/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/assets/js/bootstrap.min.js"></script>


Ajitesh Kumar
Follow me

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog,
Posted in Java. Tagged with .

Leave a Reply

Your email address will not be published. Required fields are marked *