Categories: Java

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.io.IOException;
import java.io.StringReader;
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
        .withFirstRecordAsHeader().parse(sReader);
      //
      // 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 {
   request.setAttribute("message",
     "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.

<servlet>
    <servlet-name>fileIOController</servlet-name>
    <servlet-class>com.vitalflux.core.FileIOController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>fileIOController</servlet-name>
    <url-pattern>/vitalflux/uploadfile</url-pattern>
  </servlet-mapping>

 

Code Samples – UI Code

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

<!DOCTYPE html>
<html>
<title>Upload File</title>
<head>
<!-- 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">
</head>
<body class="container">
<h1>Upload the file</h1>
<hr/>
<div>
<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>
          <div class="modal-footer">              
         <button ng-if="showSubmit" class="btn btn-primary" type="submit">Submit</button>
       </div>                 
</form>
</div> 
<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>
</body>
</html>

 

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. 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.

Recent Posts

Agentic Reasoning Design Patterns in AI: Examples

In recent years, artificial intelligence (AI) has evolved to include more sophisticated and capable agents,…

3 weeks ago

LLMs for Adaptive Learning & Personalized Education

Adaptive learning helps in tailoring learning experiences to fit the unique needs of each student.…

4 weeks ago

Sparse Mixture of Experts (MoE) Models: Examples

With the increasing demand for more powerful machine learning (ML) systems that can handle diverse…

1 month ago

Anxiety Disorder Detection & Machine Learning Techniques

Anxiety is a common mental health condition that affects millions of people around the world.…

1 month ago

Confounder Features & Machine Learning Models: Examples

In machine learning, confounder features or variables can significantly affect the accuracy and validity of…

1 month ago

Credit Card Fraud Detection & Machine Learning

Last updated: 26 Sept, 2024 Credit card fraud detection is a major concern for credit…

1 month ago