File upload using commons-upload-file and tomcat 5.5

Hi,
This is my first post and I hope that I post it at the right place.
I'm trying to upload a file using commons-upload-file and tomcat 5.5.
Is there a way to prevent submitting a big file, If I detect that the file being uploaded exceed a limit that I have fixed ?
i.e. I check the request length, if it's bigger than 1meg I cancel the whole thing and the big file is not transferred.
The problem that I get at the moment is that it seems that the file is transferred even if I close request inputstream or response outputstream. Any help would be appreciated !
Thank you
Redgy

Well here is a snippet of my code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        long maxSize = 50000;
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(isMultipart){
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload();
            upload.setSizeMax(maxSize);
            try {
                upload.parseRequest(request);
            } catch (FileUploadException ex) {
                ex.printStackTrace();
                request.getInputStream().close();
                response.getWriter().print("blah");
                response.sendError(response.SC_INTERNAL_SERVER_ERROR);
                response.getOutputStream().close();
    }If the file is bigger than 50kb, it Throws the FileUploadException.
But whatever I do, It seems that there is still a connection between my browser and tomcat.. any clue ?
thanks
Edited by: redgyx on Jan 31, 2008 6:17 AM

Similar Messages

  • How to upload (.txt) file by using GUI Upload?

    I tried to upload .csv file in using GUI upload and it works.
    THIS IS MY SAMPLE CODE.
    CLEAR w_rawfile.
      DESCRIBE TABLE i_rawfile LINES v_read.     "Counter for records read
      Condense w_rawfile-field.
    Separate header record from detail records
      LOOP AT i_rawfile INTO w_rawfile.
        IF sy-tabix = 1.           "header is always the first record
          SPLIT w_rawfile-field AT ' ' INTO
            w_header_file-name1
            w_header_file-name2
            w_header_file-name3
            w_header_file-cntry
            w_header_file-address1
            w_header_file-address2.
      APPEND w_header_file TO i_header_file.
          CLEAR: w_header_file.
        ELSE.            "succeeding records are detail records
          SPLIT w_rawfile-field AT ',' INTO
                 w_inputfile-nachn
                 w_inputfile-vorna
                 w_inputfile-nach2
                 w_inputfile-land1
                 w_inputfile-stras
    APPEND w_inputfile TO i_inputfile.
    ENDIF.
    IF i try to replace my file into a .txt format. An error occurs. Please kindly give me the code to do this correctlt. ThanX!

    Reading Data from Presentation Server (Dialog)
    To read data from the presentation server into an internal table with a user dialog, use the function module UPLOAD. The most important parameters are listed below. For more information, refer to the function module documentation in the Function Builder (Transaction SE37).
    Important Import Parameters
    Parameters
    Function
    CODEPAGE
    Only for upload under DOS: Value IBM
    FILENAME
    Filename (default value for user dialog)
    FILETYPE
    File type (default value for user dialog)
    ITEM
    Title for dialog box
    Use the FILETYPE parameter to specify the transfer mode. Possible values:
    BIN
    Binary files
    ASC
    ASCII files: Text files with end of line markers.
    DAT
    Excel files, saved as text files with columns separated by tabs and lines separated by line breaks.
    WK1
    Excel and Lotus files saved as WK1 spreadsheets.
    Important Export Parameters
    Parameters
    Function
    FILESIZE
    Number of bytes transferred
    ACT_FILENAME
    Filename (as entered in the user dialog)
    ACT_FILETYPE
    File type (as entered in the user dialog)
    Tables Parameters
    Parameters
    Function
    DATA_TAB
    Internal table (target for the import)
    Exceptions Parameters
    Parameters
    Function
    CONVERSION_ERROR
    Error converting data
    INVALID_TABLE_WIDTH
    Invalid table structure
    INVALID_TYPE
    Incorrect FILETYPE parameter
    Suppose the presentation server is running under Windows NT, and contains the following Excel file:
    If this table is saved as a text file "D:\temp\mytable.txt" with tabs between the columns, the following program can read the table:
    PROGRAM SAPMZTST.
    DATA: FNAME(128), FTYPE(3), FSIZE TYPE I.
    TYPES: BEGIN OF LINE,
             COL1(10) TYPE C,
             COL2(10) TYPE C,
             COL3(10) TYPE C,
           END OF LINE.
    TYPES  ITAB TYPE LINE OCCURS 10.
    DATA: LIN TYPE LINE,
          TAB TYPE ITAB.
    CALL FUNCTION 'UPLOAD'
         EXPORTING
              CODEPAGE            = 'IBM'
              FILENAME            = 'd:\temp\mytable.txt'
              FILETYPE            = 'DAT'
              ITEM                = 'Read Test for Excel File'
         IMPORTING
              FILESIZE            =  FSIZE
              ACT_FILENAME        =  FNAME
              ACT_FILETYPE        =  FTYPE
         TABLES
              DATA_TAB            =  TAB
         EXCEPTIONS
              CONVERSION_ERROR    = 1
              INVALID_TABLE_WIDTH = 2
              INVALID_TYPE        = 3.
    WRITE: 'SY-SUBRC:', SY-SUBRC,
         / 'Name    :', (60) FNAME,
         / 'Type    :', FTYPE,
         / 'Size    :', FSIZE.
    SKIP.
    LOOP AT TAB INTO LIN.
       WRITE: / LIN-COL1, LIN-COL2, LIN-COL3.
    ENDLOOP.
    The program displays the following dialog box:
    Here, the user can change the default values. When the user chooses Transfer, the system imports the data from the file D:\temp\mytable.txt into the internal table TAB.
    The output appears as follows:
    SY-SUBRC: 0
    Name : d:\temp\mytable.txt
    Type : DAT
    Size : 69
    Billy the Kid
    My Fair Lady
    Herman the German
    Conan the Barbarian
    The contents of the internal table TAB are exactly the same as the contents of the original Excel table.

  • Using WEB Output HTML Gallery and uploading using ftp upload the HTML page views correctly but images only display the alt tag?

    Using WEB Output HTML Gallery and uploading using ftp upload the HTML page views correctly but images only display the alt tag in the browser window?

    After a little investigation, I discovered that PNGs also do not render correctly in IE7 in similar circumstances.
    I ended up using Levels in Photoshop to bring the output blacks up to "5", saved the images as PNGs, modified the HTML from .jpg to .png, and that seems to have covered up the problem well enough.
    By the way, I did confirm that IE8 beta 2 renders the images correctly.
    Brian

  • Problems getting just the file name using an upload component

    Hi everyone, I'm using an upload component on my page and I need to get just the name of the image/file in order to store it in a database, I used the code of the tutorial and It works fine on mozilla but the problem comes when I use Internet Explorer because I get the whole path of the image/file and not just the name of it. I believe the browser is the cause of the problem, I already checked the http://jakarta.apache.org/commons/fileupload/, but I don't understand how to use anything, and not even the code of the tutorial works eventhough it is specified in comments:
    // some browsers return complete path name, some don't
       // make sure we only have the file name
       String justFileName = uploadedFileName.substring
          ( uploadedFileName.lastIndexOf(File.separatorChar) + 1 );If anybody could helpme solve this problem I'd appreciate it so much
    Regards
    Yes
    Message was edited by:
    Yesenia

    Let's walk through the code...
    File.separatorChar is the system-dependent default hame-separator charac tor. This field is initialized to contain the first character of the system property file.separator. On UNIX systems, the value of this field is '/'; on Microsoft Windows systems it is '\\'.
    String justFileName =
    // get the substring of uploadedFileName
    // that starts after the last separator (\ or /)
    uploadedFileName.substring
    uploadedFileName.lastIndexOf(File.separatorChar) + 1
    You say that this statement is returning the complete path name, for example:
    C:\Documents and Settings\All
    Users\Documentos\Mis im��genes\Im��genes de
    muestra\Puesta de sol.jpgSo, we can make an assumption that the File.separatorChar must not be \, or else the statement would return Puesta de sol.jpg.
    We know that it works for you on Solaris/Mozilla.
    We also know that Misha has tested the statement in IE and it works for him.
    (And I know that this tutorial was tested by a software engineer and a quality engineer, and it worked for both of them, as well as the tutorial author and a peer).
    So, what is different here??????
    Can you print out File.separatorChar and see if it is '\\' (I think the first \ is an escape char, that is \\ (escape-escape) is the equivalent of \ (backslash)) or '\'?
    When you run it on another machine, how are you deploying it on the other machine? Is it deployed to Solaris and running on Windows?
    Have you tested to see if it works on a Windows machine using Mozilla?
    Thanks in advance for any light you can shed on the problem.

  • How to declare variable in solution file for use in project files.

    Hi Folks,
    Apologies if this is not the right place to ask, but I would like to declare a variable in my solution file that can used by all of the projects (prof files) in that solution.
    More specifically in the project files, references are stored using relative paths which cause issues if they don't exist. I would like to replace the relative paths with a variable set in the solution file that can easily be changed when the solution is
    built in a different location.
    So I would like to replace "../../../SomeProject"  with "$(SomeLocation)/SomeProject"  but set the $(SomeLocation) in the solution file.
    Regards
    Andy

    Hello Andy,
    Here is a common sln file:
    Microsoft Visual Studio Solution File, Format Version 12.00
    # Visual Studio 2013
    VisualStudioVersion = 12.0.30723.0
    MinimumVisualStudioVersion = 10.0.40219.1
    Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "wpf_EntityFramework", "wpf_EntityFramework\wpf_EntityFramework.csproj", "{A282940A-5F76-4FF8-9568-8B7D14133259}"
    EndProject
    Global
    GlobalSection(SolutionConfigurationPlatforms) = preSolution
    Debug|Any CPU = Debug|Any CPU
    Release|Any CPU = Release|Any CPU
    EndGlobalSection
    GlobalSection(ProjectConfigurationPlatforms) = postSolution
    {A282940A-5F76-4FF8-9568-8B7D14133259}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    {A282940A-5F76-4FF8-9568-8B7D14133259}.Debug|Any CPU.Build.0 = Debug|Any CPU
    {A282940A-5F76-4FF8-9568-8B7D14133259}.Release|Any CPU.ActiveCfg = Release|Any CPU
    {A282940A-5F76-4FF8-9568-8B7D14133259}.Release|Any CPU.Build.0 = Release|Any CPU
    EndGlobalSection
    GlobalSection(SolutionProperties) = preSolution
    HideSolutionNode = FALSE
    EndGlobalSection
    EndGlobal
    And the Global Interface in the solution file is actually used for Visual Stuido add-ins. To know details, please read the following MSDN article:
    1. Persisting Information in Projects and Solutions
    Here you can find "If the Globals object is associated with the
    Solution2 object, then the value persists in the .sln file. These values are persisted when the solution file is saved."
    2.
    Solution2 Interface
    It's about the solution interface.
    As you can see although they may save something to your solution file, it is not intended for you to use it in your project.
    What's your projec type and can you alter to use some common ways?
    For example:
    1. If it is in project level, set your value public so that all classes can access the value.
    2. Or you can choose to create a xml/text file or any file that you can read by code, and then read the value out from that file.
    It will be much better than thinking about set value in the solution file.
    Best regards,
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to pick the sender files dynamically using the same File CC

    hi,
    My requirements is like , Same Sender File communication Channel has to pick up the different file which are having differnt file conventions and which are placed in different directories .. then it has to send to diffentn directories in the receiver side..
    how to do this?
    Regards,
    Balaji

    Hi Stefen,
    They have tried the Generic Sender File adapter concept to handle filenames with different names and from different directories instead creating many file channels. In my project many channels are configured as generic File sender channel.. And Eventhough the Generic file sender channels processing the filenames from different directories, all processed files are archieved in one common directories.. now they wanna generic solution to archieve the processed files in a particular folder based upon the directories they got processed from....
    and There are no such message mapping or Operation mapping since they used AAE concept. So do you  have any idea to make Generic File sender channels to archieve the files as per requirements i said before??
    Two doubts can we use like Module programming or can we do any OS level command acchieve this ? if yes please explain in detail .... Please help me out here
    please refer the following link .. exact way we used in our project
    http://wiki.sdn.sap.com/wiki/display/XI/SingleSenderFileCCForMultipleDirectories
    Regards,
    Balaji
    Edited by: Balaji Pichaimuthu on Feb 5, 2010 5:55 AM

  • Getting a file name using java.io.file

    Dear List,
    I am having problems using java.io package. I am reading a string on a linux tomcat server. I am
    trying to parse a windows type filepath (passed by a web-browser-client) and get only the filename. ie. sample.jpg.
    fileName = "c:\\temp\\sample.jpg"
    java.io.File file = new File(fileName);
    onlyFileName = file.getName();
    remember this on linux, and on my server onlyFileName contains "c:\\temp\\sample.jpg" and not sample.jpg as I would expect.
    can any one tell me what I (yet again) dont understand.? Strangely enough when the server is on windows and I am passing a linux string with the fileseperator as a forward-slash, the code manages to derive the correct filename.
    regards
    Ben

    Post this to the beginners forum - has nothing to do
    with native methods.Apologies I thought Java.io would be "native".
    sorry,
    BB

  • How to get value of jca.file.IsEof using fromproperties in file adapter

    Hi Guys,
    I have a scenario where i use a file adapter for syncread (for doing chunkRead).
    While invoking this adapter i send jca.file.FileName and jca.file.Directory as input properties dynamically.
    In response i expect jca.file.IsEOF and jca.file.IsMessageRejected, for this i have done the following steps.
    1. Create a file adapter for SyncRead
    2. Create an invoke activity and input/output variables along with it.
    3. set input properties as below ..
    4. get the values of jca.file.IsEOF and jca.file.IsMessageRejected using bplex:fromproerties
    <invoke name="Invoke1"
    inputVariable="Invoke1_SynchChunked_InputVariable"
    outputVariable="Invoke1_SynchChunked_OutputVariable"
    partnerLink="SamplSyncChunkRead"
    portType="ns19:SynchChunked_ptt"
    operation="SynchChunked"
    bpelx:invokeAsDetail="no">
    <bpelx:inputProperty name="jca.file.FileName"
    variable="inputVariable"
    part="payload"
    query="/ns11:fileHeader/ns11:fileName"/>
    <bpelx:inputProperty name="jca.file.Directory"
    variable="inputVariable"
    part="payload"
    query="/ns11:fileHeader/ns11:directory"/>
    <bpelx:fromProperties>
    *<bpelx:fromProperty name="jca.file.IsEOF" variable="isEndofFile"/>*
    *<bpelx:fromProperty name="jca.file.IsMessageRejected" variable="istheMessageRejected"/>*
    </bpelx:fromProperties>
    </invoke>
    5. Flow of the project is fine but im not getting the fromProperty values assigned to variables.
    Note : rather using from proerties like give below
    <bpelx:fromProperties>
    *<bpelx:fromProperty name="jca.file.IsEOF" variable="isEndofFile"/>*
    *<bpelx:fromProperty name="jca.file.IsMessageRejected" variable="istheMessageRejected"/>*
    </bpelx:fromProperties>
    if i use output proerties as given below it is not working..
    <bpelx:outputProperty name="jca.file.isEOF" variable="isEndofFile"/>
    <bpelx:outputProperty name="jca.file.IsMessageRejected" variable="istheMessageRejected"/>
    Any suggestions on this ???
    Thanks in advance guys...

    Thanks veejai...
    i have used the following properties in my code..
    <bpelx:fromProperties>
    <bpelx:fromProperty name="jca.file.IsEOF" variable="isEndofFile"/>
    <bpelx:fromProperty name="jca.file.IsMessageRejected" variable="istheMessageRejected"/>
    </bpelx:fromProperties>
    if i use output proerties as given below it is not working..
    <bpelx:outputProperty name="jca.file.isEOF" variable="isEndofFile"/>
    <bpelx:outputProperty name="jca.file.IsMessageRejected" variable="istheMessageRejected"/>
    any suggestion on <bplex:fromproperties> ??

  • How to call Fortran .dll file that using other library files?

    Hi,
    I am trying to do some arkward tasks using LabView, and I am desperately need help....
     A little bit background:
    1. My co-worker has some code written in Fortran, where he called other libraries (many from CERNLAB or PAW). Those stuffs are pretty powerful in mathmatical calculation and simulations.
    2. In some of my LabView code, I need to call his Fortran source code in order to do some complicated calculations. I have no capablility to translate his Fortran code to Labview (or is it even possible??), so we end up with trying to use "Call library function node" where I just provide input/outputs to communicate with his code. The idea sounds simple enough?
    3. We complie the Fortran code into .dll, and then specifiy the dll in "Call library function node". The first try with a very simple Fortran code, something like c = a+b*a, was sucessful. The dll file and Call lib function worked good. It's sort of proved the concept.
    4. Now I am trying more complicated Fortran code (say Test.dll), which calling other library (.lib files) that using typical "call xxx(a,b,c)" line, and my nightmare started....  It seems nothing was excuted when I call Test.dll in LabView.
    Questions:
    1. How do LabView know if the Test.dll code needs functions from other .lib files? Do I need to copy all the .lib files to a specific folder?
    2. When I create .dll file, for LabView to be able to use it, are there any special requirement on the way the .dll is compiled?
    3. Seems there is mismatch btw the data type in Fortran and LabView. For example, LabView's  Signed 8-bit Integer seems different with a integer in Fortran. How can i know the correlation btw data type in different langurage, i.e. LabView vs Fortran?
    4. Are there any good examples that I can take a look?
    I would highly appreicate any suggestions/helps!
    Rgds,
    Harry

    You are aware that Intel Visual Fortran is the successor to Compaq Visual Fortran (I think you made a mistype with the Virtual)? So an upgrade might be at its place.
    Anyhow I'm really not familiar with Fortran at all, but lib files are usually compiled into an EXE or DLL and not loaded dynamically. 1) 
    So there should be no problem with locating those libs. What most likely is a problem are other DLL dependencies such as any Fortran Runtime library or possibly other third party DLLs the more advanced code in your DLL might be using.
    Typically most compilers can be configured to link the runtime library code statically into the DLL, as altenbach reports for the Intel compiler, otherwise you must make sure to install the  redistributable Fortran Runtime Library for your compiler. Besides that you must make sure to find out what other runtime dependencies your code might have and install them.
    1) One exception I know of is LabWindows CVI which allows to also load lib files dynamically. This is supposedly a legacy feature from LabWindows for DOS, which allowed that feature to simulate dynamic module loading in order to swap modules at runtime to work around the 640k memory limitation of DOS.
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • How to run java file by using another applet file  ??

    how to compile and run java file by using another applet or japplet file .

    how to understand what you are talking about.

  • Exception while excel processing after upload using commons file upload

    Hi all,
    I am experiencing problem while creating a workbook after getting the input stream from the uploaded file. its not going catch block instead it is going to finally and giving null pointer exeption in finally as one variable in finally is not defined. the variable is defined in try as well as catch but during run time the variable is not getting assigned any value also. I'll put the code over here. please help me with a solution
    import org.w3c.dom.* ;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import jxl.*;
    import org.apache.commons.fileupload.*;
    import org.apache.commons.fileupload.disk.*;
    import org.apache.commons.fileupload.servlet.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    public class CescoreUploadServlet extends baseHttpServlet
         private DataSource cesDS = null;
         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
              doPost(req, res);
         public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
              String targetPage = null;
              File f = null;
              System.out.println("Upload Controller");
              HttpSession session = req.getSession(true);
              try
                   if(cesDS == null){
                        cesDS = new JNDIDataSource(getServletContext().getInitParameter(Constants.DATA_SOURCE_NAME));
                   CesRepository cRep = new CesRepository(cesDS);
                   if (session.getAttribute("DataContainerInfo") == null) {
                        System.out.println("Initializing DataContainerInfo");
                        DataContainer DataContainer = new DataContainer();
                        cRep.setInitialParameters(DataContainer);
                        session.setAttribute("DataContainerInfo",DataContainer);
                   else System.out.println("DataContainerInfo is available");
                   UserInfo userInfo = null;               
                   String login_id = req.getRemoteUser();
                   if(session.getAttribute("UserID") != null) login_id = (String)session.getAttribute("UserID");
                   if(session.getAttribute("userProfile") == null ) session.setAttribute("userProfile", cRep.getUserInfo(login_id));
                   userInfo = (UserInfo)session.getAttribute("userProfile");
                   System.out.println("<<<<<< userInfo contains : "+userInfo.getHrID()+" >>>>>>");
                   String projIdValue = null;
                   String msg = null;
                   boolean isMultipart = FileUpload.isMultipartContent(req);
                   if(isMultipart){
                        System.out.println("is MultiPart");
                        DiskFileUpload upload = new DiskFileUpload();
                        List fileList = upload.parseRequest(req);
                        InputStream uploadedFileStream = null;
                        String uploadedFileName = null;
                        ArrayList impArray = new ArrayList();
                        Iterator iter = fileList.iterator();
                        while (iter.hasNext()) {
                             System.out.println("inside while");
                             FileItem item = (FileItem) iter.next();
                             if (!item.isFormField()) {
                                  System.out.println("item is not form field");
                                  if (item.getSize() < 1)
                                       throw new Exception("No file was uploaded");
                                  else
                                       uploadedFileName = item.getName();
                                       System.out.println("uploaded file name "+uploadedFileName);
                                       System.out.println("uploaded file size is "+item.getSize());
                                       uploadedFileStream = item.getInputStream();
                                       System.out.println("uploaded input stream available size is "+uploadedFileStream.available());
                             else
                                  System.out.println("item is form field");
                                  String key     = item.getFieldName();
                                  String value = item.getString();
                                  System.out.println("key is"+key);
                                  System.out.println("value is"+value);
                                  if(key.equals("projectId2")){
                                       projIdValue = value;
                        System.out.println("outside while");
                        POIFSFileSystem fs = new POIFSFileSystem(uploadedFileStream);
                        System.out.println("got POIFSFileSystem");//this is been printed in logs
                        HSSFWorkbook wb = new HSSFWorkbook(fs);//it is breaking over here
                        System.out.println("got HSSFWorkbook");//this is not been printed in logs
                        HSSFSheet sheet = wb.getSheetAt(0);
                        System.out.println("got HSSFSheet");
                        Iterator rows = sheet.rowIterator();
                        if(rows.hasNext()){
                        while( rows.hasNext() ) {
                             System.out.println("rows iteration");
                             HSSFRow row = (HSSFRow) rows.next();
                             Iterator cells = row.cellIterator();
                             while( cells.hasNext() ) {
                                  System.out.println("cell iteration");
                                  HSSFCell cell = (HSSFCell) cells.next();
                                  HashMap hm = new HashMap();//if everything is fine i'll use this hashmap to store values
                             System.out.println("CES UPLOAD.SERVLET. After adding");
                             msg = "Attendees have been added successfully";
                             req.setAttribute("msgText", msg);
                             targetPage = "/ces_disp.jsp";
                        else
                             throw new Exception("The Excel Sheet Uploaded has no entries. Please check and try again");
                   else{
                        throw new Exception("The Form is not Multipart");
              catch (Exception e)
                   System.out.println("CES UPLOAD.SERVLET.EXCEPTION ::: Exception");
                   targetPage = "/ces_disp.jsp";
                   if(e != null) req.setAttribute("msgText", e.getMessage());
                   else req.setAttribute(Constants.EXCEPTION_ATTR_NAME, new Exception("Unknown Exception"));
                   e.printStackTrace();
              finally{
                   System.out.println("CES UPLOAD.SERVLET. ::: Finally");
                   ServletContext stx = getServletConfig().getServletContext();
                   RequestDispatcher dispatcher = sCx.getRequestDispatcher(targetPage);
                   dispatcher.forward(req, res);
    Message was edited by: Noufal
    Noufal_k
    Message was edited by:
    Noufal_k

    import org.w3c.dom.* ;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import jxl.*;
    import org.apache.commons.fileupload.*;
    import org.apache.commons.fileupload.disk.*;
    import org.apache.commons.fileupload.servlet.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    public class CescoreUploadServlet extends baseHttpServlet
    private DataSource cesDS = null;
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    doPost(req, res);
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    //including only relevant code
    String targetPage = null;
    System.out.println("Upload Controller");
    HttpSession session = req.getSession(true);
    try
    String projIdValue = null;
    String msg = null;
    boolean isMultipart = FileUpload.isMultipartContent(req);
    if(isMultipart){
    System.out.println("is MultiPart");
    DiskFileUpload upload = new DiskFileUpload();
    List fileList = upload.parseRequest(req);
    InputStream uploadedFileStream = null;
    String uploadedFileName = null;
    Iterator iter = fileList.iterator();
    while (iter.hasNext()) {
    System.out.println("inside while");
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField()) {
    System.out.println("item is not form field");
    if (item.getSize() < 1)
    throw new Exception("No file was uploaded");
    else
    uploadedFileName = item.getName();
    System.out.println("uploaded file name "+uploadedFileName);//printing  c:/excelsheets/fileToUpload.xls
    System.out.println("uploaded file size is "+item.getSize());//printing size is 15872
    uploadedFileStream = item.getInputStream();
    System.out.println("uploaded input stream available size is "+uploadedFileStream.available());//printing available input stream size is 15872
    else
    System.out.println("item is form field");
    String key = item.getFieldName();
    String value = item.getString();
    System.out.println("key is"+key);
    System.out.println("value is"+value);
    if(key.equals("projectId2")){
    projIdValue = value;
    System.out.println("outside while");
    POIFSFileSystem fs = new POIFSFileSystem(uploadedFileStream);
    System.out.println("got POIFSFileSystem");//this is been printed in logs
    HSSFWorkbook wb = new HSSFWorkbook(fs);//it is breaking over here
    System.out.println("got HSSFWorkbook");//this is not been printed in logs
    HSSFSheet sheet = wb.getSheetAt(0);
    System.out.println("got HSSFSheet");
    Iterator rows = sheet.rowIterator();
    if(rows.hasNext()){
    while( rows.hasNext() ) {
    System.out.println("rows iteration");
    HSSFRow row = (HSSFRow) rows.next();
    Iterator cells = row.cellIterator();
    while( cells.hasNext() ) {
    System.out.println("cell iteration");
    HSSFCell cell = (HSSFCell) cells.next();
    HashMap hm = new HashMap();//if everything is fine i'll use this hashmap to store values
    System.out.println("CES UPLOAD.SERVLET. After adding");
    msg = "Attendees have been added successfully";
    req.setAttribute("msgText", msg);
    targetPage = "/ces_disp.jsp";
    else
    throw new Exception("The Excel Sheet Uploaded has no entries. Please check and try again");
    else{
    throw new Exception("The Form is not Multipart");
    catch (Exception e)
    System.out.println("CES UPLOAD.SERVLET.EXCEPTION ::: Exception");
    targetPage = "/ces_disp.jsp";
    if(e != null) req.setAttribute("msgText", e.getMessage());
    else req.setAttribute(Constants.EXCEPTION_ATTR_NAME, new Exception("Unknown Exception"));
    e.printStackTrace();
    finally{
    System.out.println("CES UPLOAD.SERVLET. ::: Finally");
    ServletContext stx = getServletConfig().getServletContext();
    RequestDispatcher dispatcher = stx.getRequestDispatcher(targetPage);//throwing null pointer exception for this line
    dispatcher.forward(req, res);
    }

  • Is there a fix for terrible performance of file transfers using finder via CIFS and SMB?

    I am connecting to an EMC VNXe running Celera file server and am getting abysmal file transfer performance using both CIFS and SMB-  what gives? This seems to be a long-standing issue- any good work-arounds or solutions?

    I rarely see cover art issues unless the cover art embedded in the file is poor to begin with.
    1000x1000 is probably overkill anyway (and if you had several 1000 large cover art images, could eat at AppleTV's memory) though I must admit I always try to get good hi-res images and don't like anything much below 500x500 or 600x600.  There's no hard and fast rule but even a few 300x300 images I have look reasonable at normal viewing distance.
    I wonder as you say if it might be an issue with iTunes for Windows as I'm on OS X.  Actually that reminds me of another issue I have.
    AC

  • I can no longer use the Option key to download a file. Using FF 13.0 and Mac OS 10.7.3

    Is there a preferences setting? It always worked before. I think I may have updated to 13 since I last tried?

    Yes, this changed in Firefox 13:
    https://bugzilla.mozilla.org/show_bug.cgi?id=713052
    To re-enable the old behavior, type "about:config" in the address bar, then search for browser.altClickSave and double-click to change its value to "true".

  • File size (using java.io.File)

    Hello all,
    When I want to create an app to be used as file browser, I should like to know the size of a file in a directory. The java.io.File class gives me quite some functionality, but not the functionality to display the file size.
    Does anyone know of a default class that has the functionality to display the file size?
    When no such class exists, I should need to develop it myself. From the top of my head it should be something like this:
    int size = 0;
    int aChar = 0;
    FileReader reader = new FileReader (theFile);
    while (reader.ready() )
        aChar = reader.read()
        size++;
    }The variable size gives me now the number of characters in a file. But this should be done for each file in a particular directory. But does that not ask much CPU performance? Does anyone have an alternative?
    Looking forward to your answer
    Michel

    Hi, I'm having the exact same problem, except that I'm doing a fax system so I can't copy a file while the file is still open. So to check to see if the file is open I have to check the file size in bytes then wait a second and check the file size again. If the file sizes differ then I have to check the next file otherwise I can copy the file. I had a look at the length() method but that will only return the actual length of the file name, not the size of the contents of the file which I need, can anyone please help? Say the file name is 16 ad an a or anything to the file name, if you the call the length() method again it will return 17.

  • Anyone using FCP's file manager to remotely share files, anyone using FCP's file manager to remotely share files?

    Hi:
    I am looking to build a solution for a prospective client.  I want to use FCP server's file manager to allow remote users to access and obtain content.  This arrangement is actually for healthcare solution. I know FCP is used to manage and transfer files, but I am not sure what controls, access, etc are available to make assurances these files are not manipulated.

    I've been using FCP for a long time and I do not know of "file manager" tool. Are you looking for an evaluation of FCP Server? That's a different forum, not many users of that app here.
    bogiesan

Maybe you are looking for

  • ITunes Converter Not Working

    I am trying to convert a downloaded MPEG-4 file in ITunes for use on my Ipod. The converter runs through it and when complete, I get a file with no video, just sound. Any ideas?

  • Idoc to txt file to mail

    Hello everyone, I have the following scenario: IDOC -> XI -> Mail w/ .txt attach with fields of IDOC separated by ';' How can i "concatenate" all fields into one text file and then send this in an attachment via email ?                    Thank you i

  • Dead iBook...Way to deauthorize it from another computer?

    Yesterday the hard drive died in my iBook G4, and I have had a backup of all of the music on an external drive. I've put all of this music onto my old Windows desktop (sigh...). However, I am unable to authorize my desktop computer because the iBook

  • General information about JATO.

    OK, We are finally ready to get off of ND4. I'm doing some research about our next direction. The way I understand it is that iMT will transform my ND apps into J2EE apps using the JATO architecture. Where can I find more information about JATO? I ca

  • Static blocks and synchronization

    Hi, I have a question - I have a DAO class which basically caches some master data, and also reads a property file and caches the information. To do this I have written a static block : Class MyDAO { private static Properties sqlProp = null; priate H