I am trying to upload a .xls file which is in my Downloads drive. The file link is C:\Users\pch\Downloads. When I move it to my C:\ and upload it, it runs fine but when it's in my download drive it doesn't. I am getting a "File not found" error.
Here is what I tried.
//Create a new file upload handler.
ServletFileUpload upload = new ServletFileUpload();
//Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
System.out.println("File field " + name + " with file name " + item.getName() + " detected.");
String filename = item.getName();
// Process the input stream
File f = new File("/"+item.getName());
System.out.println(f.getAbsolutePath());
Process Excel file:
if (filename.endsWith(".xls") || filename.endsWith(".XLS")){
FileInputStream inputStream = new FileInputStream(f.getAbsolutePath()); //code breaks right here
//FileInputStream inputStream = new FileInputStream(new File(filename));
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
HSSFSheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> rows = firstSheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator<Cell> cells = row.cellIterator();
List cellData = new ArrayList();
//Skip the first row beacause it will be header
if (row.getRowNum() == 0) {
maxDataCount = row.getLastCellNum();
continue;
}
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
//Cell cell = (Cell) cells.next();
if(cell.getCellType() == Cell.CELL_TYPE_STRING) {
cellData.add(cell.getStringCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cellData.add((int)cell.getNumericCellValue());
}
}
excelData.add(cellData);
}
inputStream.close();
else {
out.println("<span style=\"color:red;\">File needs to have an extension of '.xlsx or .xls'. Hit <a href=\"javascript:window.history.go(-1)\">back</a> and try a different file.</span>");
}
}
Any help is greatly appreciated. Thank you in advance.