如何使用jsp和servlet将多个csv文件上传到mysql数据库中? [英] How to uploading multiple csv file into mysql database using jsp and servlet?

查看:66
本文介绍了如何使用jsp和servlet将多个csv文件上传到mysql数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须上传多个.csv文件,例如我有五个文本框,并且对于每个文本框,将存在相应的浏览按钮.当我单击提交按钮时,它必须在mysql数据库中使用文本框值的名称创建表,并且该表必须使用.csv文件进行更新.请有人可以建议我该怎么做.

I have to upload multiple .csv files,like I have five text boxes and for each text boxe corresponding browse button will be there . When I click on submit button, it has to create table in mysql database with name of text box value, and this table has to updated with .csv file.please can any one suggest me to how to do it.

谢谢.

这是我的代码.

servlet.java:

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:

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

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>

推荐答案

我想这会给你一个主意:D使用数组进行多次上传,而不是使用许多上传按钮.

I think this will give you idea :D use array for multi uploading rather than using many upload button.

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

这篇关于如何使用jsp和servlet将多个csv文件上传到mysql数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆