如何使用jsp和servlet将多个csv文件上传到mysql数据库?

时间:2013-10-19 07:18:58

标签: java mysql jsp csv

我必须上传多个.csv文件,就像我有五个文本框一样,每个文本框都会有相应的浏览按钮。当我点击提交按钮时,它必须在mysql数据库中创建具有文本框值名称的表,并且该表必须用.csv文件更新。请任何人建议我如何操作。

谢谢。

这是我的代码。

servlet.java:

   import java.io.File;
   import java.io.IOException;
   import java.io.PrintWriter;
   import java.util.Iterator;
   import java.util.List; 
   import javax.servlet.RequestDispatcher;
   import javax.servlet.ServletConfig;
   import javax.servlet.ServletException;
   import javax.servlet.http.HttpServlet;
   import javax.servlet.http.HttpServletRequest;
   import javax.servlet.http.HttpServletResponse;
   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;

    public class CommonsFileUploadServlet1 extends HttpServlet {
private static final String TMP_DIR_PATH=System.getProperty("user.home"); 
private File tmpDir;
private static final String DESTINATION_DIR_PATH ="/";
private File destinationDir; 
public void init(ServletConfig config) throws ServletException {

            super.init(config);
    tmpDir = new File(TMP_DIR_PATH);
    if(!tmpDir.isDirectory()) {
        throw new ServletException(TMP_DIR_PATH + " is not a directory");
    }

    String realPath =getServletContext().getRealPath(DESTINATION_DIR_PATH);
    destinationDir = new File(realPath);



}

protected void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    response.setContentType("text/plain");


    DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
    /*
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
    /*
     * Set the temporary directory to store the uploaded files of size above threshold.
     */
    fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
                int check=0;
                String name1[]=new String[30];
                String name2[]=new String[30];
                String name3[]=new String[30];
                String filename[]=new String[30];

        List items = uploadHandler.parseRequest(request);
        Iterator itr = items.iterator();
        while(itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if(item.isFormField()) {

                                    if(item.getFieldName().equals("text1"))
                                    {
                                       String name1[i]=item.getString();


                                    }
                                    if(item.getFieldName().equals("text2"))
                                    {
                                        String name2[i]=item.getString();

                                    }
                                    if(item.getFieldName().equals("text3"))
                                    {
                                        String name3[i]=item.getString();

                                    }
                                    if(item.getFieldName().equals("check"))
                                    {
                                        check=Integer.parseInt(item.getString());

                                            }

            } else {
                //Handle Uploaded files.

                                  String filename[i]=item.getName();


            }
                          i++;  
        }

                    request.setAttribute("name1",name1);
                    request.setAttribute("name2",name2);
                    request.setAttribute("name3",name3);
                    request.setAttribute("filename",filename);


                     if(check==1)
                    {
                    RequestDispatcher dispatcher = request.getRequestDispatcher("programmelink.jsp");
    if (dispatcher != null){
            dispatcher.forward(request, response);
    } 
                    }


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

} 
}

programmelink.jsp:

<%@page import="com.hcu.mysql.connection.ConnectionDemo1"%>
<%@include file="dbconnection.jsp"%>
<%@page import="java.sql.*"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.File"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<center>
<table border="2">
<%
    String pname[]=(String[])request.getAttribute("name1");
    String saveFile[]=(String[])request.getAttribute("filename");
    Statement st1=con.createStatement();
    Statement st2=con.createStatement();


try
  {
   int i;
    for(i=0;i<pname.length;i++)
   {

 pname[i]=pname[i].replace('-', '_');
 String realPath =getServletContext().getRealPath("/");

File f1 = new File(realPath+saveFile[i]);

File f2 = new File("/var/lib/mysql/dcis_attendance_system/"+saveFile[i]);
InputStream in = new FileInputStream(f1);

OutputStream out1 = new FileOutputStream(f2);

byte[] buf = new byte[1024];
int len;

while ((len = in.read(buf)) > 0){
 out1.write(buf, 0, len);
} 



Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("driver connected");   

st1.executeUpdate("create table if not exists "+pname[i]+"_curriculum(subjid      varchar(20),subjname varchar(100),credits varchar(20),semister varchar(20),sno INT) ");


  String qry2="LOAD DATA INFILE '"+saveFile[i]+"' INTO TABLE "+pname[i]+"_curriculum  FIELDS     TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n'  (subjid,subjname,credits,semister,sno)"; 

st2.executeUpdate(qry2);   

}
    out.println("<center><h1>File uploaded sucessfully</h1></center>"); 
 }
  catch(Exception e)
                       {
      out.println("<center><h1>File not uploaded sucessfully</h1></center>");

  }
     %>
</table>
</center>

jsppage.jsp

 <form action="servlet" enctype="multipart/form-data" method="POST">
                <input type="hidden" name="check" value="7" />   



    </table>

         <table align="center" border="1" id="table1">
        <tr>

            <td class="heading" align="center">Programme Name</td>
            <td class="heading" align="center">Programme Code</td>
            <td class="heading" align="center">Browse Curriculum</td>
            </tr>
            <%int i;
            for(i=0;i<2;i++)

            {
            %>
            <tr>
                <td><input type="text" name="text1"  size="11"  value=""> </td> 
                <td><input type="text" name="text2"  size="10" value=""> </td>
                <td><input type="file" name="file1" class="multi" id="file"></td>
           </tr> 
           <%}%>
           </table>

           <table align="center">
            <tr>
                <td><input type="submit" name="submit" value="submit"></td>&nbsp;
                <td><input type="button" name="add" value="Add" onclick="next();"></td>&nbsp;
            </tr>                             
        </table>

    </form>

1 个答案:

答案 0 :(得分:0)

我认为这会给你一个想法:D使用数组进行多重上传,而不是使用很多上传按钮。

<td><input type="file" name="file[]" class="multi" id="file"></td>