загрузка файла excel с помощью загрузки файла apache

Я разрабатываю инструмент автоматизации тестирования в системе Linux. У меня нет прав на запись для каталога tomcat, который находится на сервере. Мне нужно разработать приложение, в котором мы можем выбрать файл Excel, чтобы содержимое Excel автоматически сохранялось в уже существующей таблице.

Для этой цели я написал форму для выбора файла, который отправляется в сервлет CommonsFileUploadServlet, где я сохраняю загруженный файл, а затем вызываю класс ReadExcelFile, который считывает путь к файлу и создает вектор для данных в файле, который используется для хранения данных. в базе данных.

Моя проблема в том, что я не могу сохранить загруженный файл в каталоге. Нужно ли иметь права доступа для tomcat, чтобы сделать это. Могу ли я сохранить файл в своей системе и передать путь к ReadExcelFile.class

Пожалуйста, направь меня

Мой код выглядит следующим образом:

Форма в JSP

Код класса CommonsFileUploadServlet:

public void init(ServletConfig config) throws ServletException {
    super.init(config);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");
    out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
    DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
    fileItemFactory.setSizeThreshold(1*1024*1024);
    fileItemFactory.setRepository(new File("/home/example/Documents/Project/WEB-INF/tmp"));
    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        List items = uploadHandler.parseRequest(request);
        Iterator itr = items.iterator();
        while(itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if(item.isFormField()) {
            out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
            } else {
                out.println("Field Name = "+item.getFieldName()+
                    ", File Name = "+item.getName()+
                    ", Content type = "+item.getContentType()+
                    ", File Size = "+item.getSize());
            File file = new File("/",item.getName());
                   String realPath = getServletContext().getRealPath("/")+"/"+item.getName();   
                item.write(file);
        ReadExcelFile ref= new ReadExcelFile();
            String res=ref.insertReq(realPath,"1");
            }

            out.close();
        }
    }catch(FileUploadException ex) {
        log("Error encountered while parsing the request",ex);
    } catch(Exception ex) {
        log("Error encountered while uploading file",ex);
    }

} }

Код ReadExcelFile:

public static String insertReq (String fileName, String sno) {

    //Read an Excel File and Store in a Vector

   Vector dataHolder=readExcelFile(fileName,sno);

//store the data to database
   storeCellDataToDatabase(dataHolder);

}
public static Vector readExcelFile(String fileName,String Sno)
{
    /** --Define a Vector
        --Holds Vectors Of Cells
     */
    Vector cellVectorHolder = new Vector();
        try{
    /** Creating Input Stream**/
    //InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
    FileInputStream myInput = new FileInputStream(fileName);

    /** Create a POIFSFileSystem object**/
    POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);

    /** Create a workbook using the File System**/
     HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int s=Integer.valueOf(Sno);
     /** Get the first sheet from workbook**/
    HSSFSheet mySheet = myWorkBook.getSheetAt(s);

    /** We now need something to iterate through the cells.**/
      Iterator rowIter = mySheet.rowIterator();

      while(rowIter.hasNext())
{
          HSSFRow myRow = (HSSFRow) rowIter.next();
          Iterator cellIter = myRow.cellIterator();
          Vector cellStoreVector=new Vector();
          short minColIndex = myRow.getFirstCellNum();
    short maxColIndex = myRow.getLastCellNum();
    for(short colIndex = minColIndex; colIndex < maxColIndex; colIndex++)
 {
 HSSFCell myCell = myRow.getCell(colIndex);
if(myCell == null)
 {
    cellStoreVector.addElement(myCell);
}
else 
{
cellStoreVector.addElement(myCell);
}
}
             cellVectorHolder.addElement(cellStoreVector);
    }
    }catch (Exception e){e.printStackTrace(); }
    return cellVectorHolder;
}

private static void storeCellDataToDatabase (Vector dataHolder) {

    Connection conn;
    Statement stmt;
    String query;

    try
    {
        // get connection and declare statement
        int z;
          for (int i=1;i<dataHolder.size(); i++)
          {
                z=0;
              Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
              String []stringCellValue=new String[10];
       for (int j=0; j < cellStoreVector.size();j++,z++)
       {
           HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
          if(myCell==null)
    stringCellValue[z]=" ";
    else
    stringCellValue[z] = myCell.toString();
        }

    try
        {
            //inserting into database
        }
        catch(Exception error)
        {
            String e="Error"+error;
            System.out.println(e);
        }
          }
        stmt.close();
        conn.close();

        System.out.println("success");
    }
    catch(Exception error)
    {
        String e="Error"+error;
        System.out.println(e);
    }

}

person user662175    schedule 07.06.2011    source источник


Ответы (1)


POI с радостью откроется из старого InputStream, это не обязательно должен быть файл.

Я предлагаю вам взглянуть на Commons FileUpload Streaming API и подумать о том, чтобы просто передать часть Excel прямо в POI, не касаясь диска

person Gagravarr    schedule 08.06.2011