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>
Latest posts by Ajitesh Kumar (see all)
- Agentic Reasoning Design Patterns in AI: Examples - October 18, 2024
- LLMs for Adaptive Learning & Personalized Education - October 8, 2024
- Sparse Mixture of Experts (MoE) Models: Examples - October 6, 2024
I found it very helpful. However the differences are not too understandable for me