Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7954937
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T03:35:00+00:00 2026-06-04T03:35:00+00:00

I am trying to upload a file to web server and read the same.

  • 0

I am trying to upload a file to web server and read the same. file uploading is working and the file is uploaded but when i call some methods to manipulate saved file the method is not getting called.

in the following file i call readFile method from post method.

I am using tomcat 7.0. Please save me from this. 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....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);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T03:35:02+00:00Added an answer on June 4, 2026 at 3:35 am

    I wanted to put it as a comment, but somehow I am unable to comment.
    My suggestion would be to debug the code using your IDE. Put breakpoints at relevant positions and see where its going.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to upload a file via URLConnection, but I need to read/write it
I'm trying to upload a file to a distant server, but looks like the
I am trying to upload files to a web server using System.Net.WebClient.UploadFile but I
I am trying to upload file from android sdcard to FTP Web server. For
I am trying to automate some upload/download tasks from an ftp web server. When
I am trying to upload file on HTTP server using POST but when I
I'm trying to customize the Liferay Web Form portlet to accept file upload, and
I was trying to upload file(s) using PrototypeJs request method but I failed. The
I'm trying to upload a file to the server using a HTTP multipart form
I'm trying trying to upload a file via Paperclip, but I'm getting an error

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.