我正在尝试将文件上传到Web服务器并阅读相同内容。文件上传工作,文件上传,但当我调用一些方法来操作保存的文件时,方法不会被调用。
在以下文件中我从post方法调用readFile方法。
我正在使用tomcat 7.0。请救救我。代码是:
package org.slingemp.fileupload;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slingemp.bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Servlet implementation class Fileupload
*/
@WebServlet("/Fileupload")
public class Fileupload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Fileupload() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("file upload started....Antony");
// TODO Auto-generated method stub
List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
// Change upload with your directory
HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(
new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(Fileupload.class.getName()).log(
Level.SEVERE, null, ex);
// Change above line replace FileUploadExample with your
// file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
}
/*
* If you want to pass some other data from JSP page.
* You can access then in this way. For each field you
* have do create if like below. if
* (fileItemTemp.getFieldName
* ().equals("Name of other field like:Firstname")) {
* String Firstname = fileItemTemp.getString(); }
*/
} else {
fileItem = fileItemTemp;
}
}
if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;
// If you want to limit the file size. Here 30MB file size
// is allowed you can change it
//if (filesize > 30.0) {
// Pass error message in session.
//setNotification _sN = new setNotification();
//_sN.setError("File size can't be more than 30MB");
//session.setAttribute("error", _sN);
//} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../accesscarddata/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"),fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("accesscardDatafileNname", _fileName);
session.setAttribute("error", _sN);
}
//}
}
//SELECT * FROM leave_application WHERE from_date >= '2004-01-01' AND to_date <'2004-01-30' and emp_id=128
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("before calling readFile");
readFile(request,response);
System.out.println("after calling readFile");
response.sendRedirect("index.jsp");
}
protected void readFile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("readFile is called..");
Map employeeMap = null;
String fileName = "",employeeAttendanceFilePath="";
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
HttpSession session = request.getSession(true);
if(session.getAttribute("accesscardDatafileNname") != null)
fileName = (String) session.getAttribute("accesscardDatafileNname");
employeeAttendanceFilePath = _uploadDir+fileName;
System.out.println("File Path : "+employeeAttendanceFilePath);
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(employeeAttendanceFilePath);
// Create an excel workbook from the file system.
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);// gets the first sheet on workbook
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
//count=count+1;
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
session.setAttribute("sheetData", sheetData);
processEmployeeAttendance(request,response);
System.out.println("employeeMap : "+employeeMap);
if(session.getAttribute("employeeMap")!=null)
employeeMap = (LinkedHashMap) session.getAttribute("sheetData");
Iterator<Map.Entry> entries = employeeMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
protected void processEmployeeAttendance(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("processEmployeeAttendance is called...");
String tempEmpid="",strdepartment="";
int j=1;
List sheetData =null;
HttpSession session = request.getSession(true);
if(session.getAttribute("sheetData")!=null)
sheetData = (ArrayList) session.getAttribute("sheetData");
Map employeeMap = new LinkedHashMap();
Map tempEmployeeMap = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
HSSFCell employeeid = (HSSFCell) list.get(0);
HSSFCell department = (HSSFCell) list.get(3);
HSSFCell date = (HSSFCell) list.get(5);
strdepartment = department.getRichStringCellValue().getString();
if(!tempEmpid.equals("")){
if(tempEmpid.equals(employeeid.getRichStringCellValue().getString()) && !(employeeid.getRichStringCellValue().getString().equals("EmpID") || date.getRichStringCellValue().getString().equals("Date") || department.getRichStringCellValue().getString().equals("Department"))){
if(!(strdepartment.equals("Temporary Card") || strdepartment.equals("Contractor"))){
employeeMap.put(employeeid.getRichStringCellValue().getString()+"_"+j,date.getRichStringCellValue().getString());
// System.out.println("j value : "+j+":"+employeeid.getRichStringCellValue().getString()+"_"+j+","+date.getRichStringCellValue().getString());
j++;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
j=0;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
}
// System.out.println("");
}
session.setAttribute("employeeMap", employeeMap);
}
}
答案 0 :(得分:1)
我想把它作为评论,但不知怎的,我无法发表评论。 我的建议是使用IDE调试代码。将断点放在相关位置并查看其进展情况。