如何使用tomcat 5.5上传excel文件?

时间:2012-05-18 07:10:14

标签: java jsp tomcat servlets file-upload

如何将文件更新到tomcat 5.5。

我尝试使用下面的代码,但代码不能与tomcat5.5一起运行并显示

Tomcat version 5.5 only supports J2EE 1.2, 1.3, and 1.4 Web module

代码是:

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....");
        // TODO Auto-generated method stub
        List fileItemsList = null;
        float filesize = 0;
        String _fileLink;
        String _fileName = null;
        String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
        System.out.println("_uploadDir :"+_uploadDir);
        // 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();
                            System.out.println("optionalFileName : "+optionalFileName);
                        }
                        /*
                         * 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();
        } finally{

        }
        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);
    }
}

当我在tomcat 7中运行此代码时,它在上传文件时会出现此错误:

java.io.FileNotFoundException: D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\Fileupload\accesscarddata\C:\Users\anthony.savarimut\Desktop\Map Iterate\SampleData.xls (The filename, directory name, or volume label syntax is incorrect)

请保存我。

1 个答案:

答案 0 :(得分:1)

您正在工作区中运行tomcat。请将位置更改为安装tomcat的位置。我假设您正在使用eclipse运行,请单击服务器并设置位置。