File upload excel文件上传使用apache文件上传

File upload excel文件上传使用apache文件上传,file-upload,apache-poi,File Upload,Apache Poi,我正在linux系统中开发一个测试自动化工具。我没有位于服务器上的tomcat目录的写入权限。我需要开发一个应用程序,我们可以选择一个excel文件,以便excel内容自动存储在现有的表中 为此,我编写了一个表单来选择一个文件,该文件被发布到一个servlet CommonFileUploadServlet,我在其中存储上传的文件,然后调用ReadExcelFile类,该类读取文件路径并为文件中的数据创建一个向量,该向量用于在数据库中存储数据 我的问题是我无法将上传的文件存储在目录中。tomca

我正在linux系统中开发一个测试自动化工具。我没有位于服务器上的tomcat目录的写入权限。我需要开发一个应用程序,我们可以选择一个excel文件,以便excel内容自动存储在现有的表中

为此,我编写了一个表单来选择一个文件,该文件被发布到一个servlet CommonFileUploadServlet,我在其中存储上传的文件,然后调用ReadExcelFile类,该类读取文件路径并为文件中的数据创建一个向量,该向量用于在数据库中存储数据

我的问题是我无法将上传的文件存储在目录中。tomcat有必要拥有这样做的权限吗。我是否可以将文件存储在系统中并将路径传递到ReadExcelFile.class

请引导我

我的代码如下:

jsp中的表单

CommonFileUploadServlet类代码:

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);
    }
public void init(ServletConfig配置)抛出ServletException{
super.init(config);
}
受保护的void doPost(HttpServletRequest请求、HttpServletResponse响应)引发ServletException、IOException{
PrintWriter out=response.getWriter();
response.setContentType(“文本/普通”);
println(“使用Commons文件上传的Servlet文件上传示例”);
DiskFileItemFactory fileItemFactory=新的DiskFileItemFactory();
fileItemFactory.setSizeThreshold(1*1024*1024);
setRepository(新文件(“/home/example/Documents/Project/WEB-INF/tmp”);
ServletFileUpload uploadHandler=新的ServletFileUpload(fileItemFactory);
试一试{
列表项=uploadHandler.parseRequest(请求);
迭代器itr=items.Iterator();
while(itr.hasNext()){
FileItem=(FileItem)itr.next();
if(item.isFormField()){
out.println(“文件名=“+item.getFieldName()+”,值=“+item.getString());
}否则{
out.println(“字段名=“+item.getFieldName()+
,File Name=“+item.getName()+
,Content type=“+item.getContentType()+
,File Size=“+item.getSize());
File File=新文件(“/”,item.getName());
字符串realPath=getServletContext().getRealPath(“/”+“/”+item.getName();
项目。写入(文件);
ReadExcelFile ref=新的ReadExcelFile();
字符串res=ref.insertReq(realPath,“1”);
}
out.close();
}
}catch(FileUploadException-ex){
日志(“解析请求时遇到错误”,例如);
}捕获(例外情况除外){
日志(“上传文件时遇到错误”,例如);
}
} }

ReadExcelFile代码:

公共静态字符串insertReq(字符串文件名,字符串sno){

//读取Excel文件并存储在向量中
Vector dataHolder=readExcelFile(文件名,sno);
//将数据存储到数据库中
storeCellDataToDatabase(数据持有者);
}
公共静态向量readExcelFile(字符串文件名,字符串Sno)
{
/**--定义一个向量
--保存细胞的载体
*/
Vector cellVectorHolder=新向量();
试一试{
/**创建输入流**/
//InputStream myInput=ReadExcelFile.class.getResourceAsStream(文件名);
FileInputStream myInput=新的FileInputStream(文件名);
/**创建一个POIFSSystem对象**/
POIFSFileSystem myFileSystem=新的POIFSFileSystem(myInput);
/**使用文件系统创建工作簿**/
HSSFWorkbook myWorkBook=新的HSSFWorkbook(myFileSystem);
int s=整数.valueOf(Sno);
/**从工作簿中获取第一张工作表**/
HSSFSheet mySheet=myWorkBook.getSheetAt;
/**我们现在需要一些东西来遍历单元格**/
迭代器rowIter=mySheet.rowitter();
while(rowIter.hasNext())
{
HSSFRow myRow=(HSSFRow)rowIter.next();
迭代器cellIter=myRow.cellIterator();
Vector cellStoreVector=新向量();
short minColIndex=myRow.getFirstCellNum();
short maxColIndex=myRow.getLastCellNum();
对于(短colIndex=minColIndex;colIndex
私有静态void storeCellDataToDatabase(向量数据持有者) {

连接连接;
报表stmt;
字符串查询;
尝试
{
//获取连接并声明语句
intz;

因为(inti=1;iPOI将很高兴地从旧的InputStream打开,它不必是文件流

<>我建议你看一下并考虑把Excel部分直接传递到POI而不接触磁盘

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

}