ksv99 ksv99 - 5 months ago 12x
Java Question

Convert a Part to File and Read Excel File

I am uploading an excel file to a servlet and trying to read its content. I am able to upload and send the file to the servlet. Over at the servlet, I am able to get the upload as a Part and read its name, file size and content type correctly. But how do I use this 'Part' to read as a file?

I am trying to use POI to read the Excel file. It requires me to pass in a file thus I passed in the 'Part' and cast it as a File. At runtime it returns an exception telling me that casting is not allowed.

I don't see a request.getFile option. Is there anyway to come around to make that Part into a File? Or another way to request File instead of Part. Please advice.

<!-- HTML -->
<form method="post" action="MyServlet" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit">Send</button>

public class ExcelUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

Part filePart = request.getPart("file");

if (filePart != null) {
// These prints out the correct data

//Need to read excel file as follows but how do I call the filepart here?
FileInputStream fis = new FileInputStream((File)filePart);//cast doesn't work
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
for(Row row : sheet){
for (Cell cell : row){


Maybe use getInputStream:

HSSFWorkbook wb  = new HSSFWorkbook(filePart.getInputStream());

Not tried but this method is in the interface of Part.