简体   繁体   中英

How to upload a excel file using tomcat 5.5?

how to update file to tomcat 5.5.

i tried with the follwoing code but the code does not run with tomcat5.5 and shows

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

the code is:

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

when i run this code in tomcat 7 it says this error when uploading the file :

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)

Please save me form this.

You are running the tomcat in workspace. Please change location to where tomcat installed. I assuming that your are running with eclipse, click on server and set the location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM