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. 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, Revive-n-Thrive.com

Recent Posts

Feature Engineering in Machine Learning: Python Examples

Last updated: 3rd May, 2024 Have you ever wondered why some machine learning models perform…

2 days ago

Feature Selection vs Feature Extraction: Machine Learning

Last updated: 2nd May, 2024 The success of machine learning models often depends on the…

2 days ago

Model Selection by Evaluating Bias & Variance: Example

When working on a machine learning project, one of the key challenges faced by data…

3 days ago

Bias-Variance Trade-off in Machine Learning: Examples

Last updated: 1st May, 2024 The bias-variance trade-off is a fundamental concept in machine learning…

3 days ago

Mean Squared Error vs Cross Entropy Loss Function

Last updated: 1st May, 2024 As a data scientist, understanding the nuances of various cost…

3 days ago

Cross Entropy Loss Explained with Python Examples

Last updated: 1st May, 2024 In this post, you will learn the concepts related to…

3 days ago