如何将CSV文件上传到JSP页面并将其中的数据发送到MySQL数据库?

huangapple go评论73阅读模式
英文:

How to upload a csv to a JSP page and send the data in it to a MySQL database?

问题

我有一个 JSP 页面,用户可以使用 `<input type="file">` 上传 CSV 文件。我希望该 CSV 文件的内容能够存储到数据库中。我花了好几个小时搜索,只找到了关于在 PHP 中处理的方法,但我对 PHP 没有任何经验,因此非常感谢提供 Java 方面的任何帮助。

我的 JSP 页面:

    <span>上传 CSV 文件:<input type="file"></span>
    
    <table style="margin-left: 20px">
        <tr>
            <th class="table-custom">员工姓名</th>
            <th class="table-custom">上班时间</th>
            <th class="table-custom">下班时间</th>
        </tr>
    </table>
英文:

I have a JSP where a user can upload a csv using input type=&quot;file&quot;. I want the content in that csv to go to a database. I searched for hours and only found methods in php for this, but I have zero experience in php, so any help in java is appreciated.

My JSP:

&lt;span&gt;Upload CSV : &lt;input type=&quot;file&quot;&gt;&lt;/span&gt;

&lt;table style=&quot;margin-left: 20px&quot;&gt;
                            &lt;tr&gt;
                                &lt;th class=&quot;table-custom&quot;&gt;Employee Name&lt;/th&gt;
                                &lt;th class=&quot;table-custom&quot;&gt;In Time&lt;/th&gt;
                                &lt;th class=&quot;table-custom&quot;&gt;Out Time&lt;/th&gt;
                                
                            &lt;/tr&gt;
&lt;/table&gt;

答案1

得分: 1

尝试这段代码:

<!-- 开始代码段: js 隐藏: false 控制台: true babel: false -->

<!-- 语言: lang-js -->

document.getElementById("upload").addEventListener("change", upload, false);
var out = "";

function upload(e) {
  document.getElementById('csvForm').innerHTML = "";

  var data = null;
  var file = e.target.files[0];

  var reader = new FileReader();
  reader.readAsText(file);
  reader.onload = function(event) {
    var csvData = event.target.result;
    var parsedCSV = d3.csv.parseRows(csvData);

    parsedCSV.forEach(function(d, i) {
      if (i == 0) return true; // 跳过标题
      if (d.constructor === Array) {
        createForm(d);
      }
    });

  }
}

function createForm(csv) {

  out += '<input value="' + csv[0] + '" name="date" type="hidden">';
  out += '<input value="' + csv[1] + '" name="name" type="hidden">';
  out += '<input value="' + csv[2] + '" name="in-time" type="hidden">';
  out += '<input value="' + csv[3] + '" name="out-time" type="hidden">';

  document.getElementById('csvForm').innerHTML = out;
  document.getElementById('csvForm').setAttribute("formmethod", "post");
  document.getElementById('csvForm').setAttribute("formaction", "testBrain.jsp");
  out += '<br>';
}

<!-- 语言: lang-html -->

<input id="upload" type="file">
<form id="csvForm"></form>
<input type="submit" value="submit" form="csvForm" formmethod="post" formaction="testBrain.jsp">
<script src="https://d3js.org/d3.v3.js"></script>

<!-- 结束代码段 -->

testBrain.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="java.sql.*,java.util.*"%>

<html>
<head>
    <meta http-equiv="Refresh" content="5;url=test.jsp">
</head>
</html>
<%
    String[] date=request.getParameterValues("date");
    String[] name=request.getParameterValues("name");
    String[] inTime=request.getParameterValues("in-time");
    String[] outTime=request.getParameterValues("out-time");

    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDb", "root", "1234");
        Statement st=conn.createStatement();

        for(int x=0; x<name.length;x++) {
            int i = st.executeUpdate("insert into csv(date,name,`in`,`out`)values('"
                                   + date[x] + "','" + name[x] + "','" + inTime[x] + "','" + outTime[x] + "')");
        }
        out.println("Data is successfully inserted! Redirecting.. Please wait");

       // String redirectURL = "test.jsp";
       // response.sendRedirect(redirectURL);

    }
    catch(Exception e)
    {
        System.out.print(e);
        e.printStackTrace();
        out.println("Error");
    }
%>

我使用了这个问题并做了一些修改使其能够工作。您可以通过在 createForm JS 中移除 &quot;type = hidden&quot; 来在提交前查看内容。

英文:

Try this code

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.getElementById(&quot;upload&quot;).addEventListener(&quot;change&quot;, upload, false);
var out = &quot;&quot;;

function upload(e) {
  document.getElementById(&#39;csvForm&#39;).innerHTML = &quot;&quot;;

  var data = null;
  var file = e.target.files[0];

  var reader = new FileReader();
  reader.readAsText(file);
  reader.onload = function(event) {
    var csvData = event.target.result;
    var parsedCSV = d3.csv.parseRows(csvData);

    parsedCSV.forEach(function(d, i) {
      if (i == 0) return true; // skip the header
      if (d.constructor === Array) {
        createForm(d);
      }
    });

  }
}

function createForm(csv) {

  out += &#39;&lt;input value=&quot;&#39; + csv[0] + &#39;&quot; name=&quot;date&quot; type=&quot;hidden&quot;&gt;&#39;;
  out += &#39;&lt;input value=&quot;&#39; + csv[1] + &#39;&quot; name=&quot;name&quot; type=&quot;hidden&quot;&gt;&#39;;
  out += &#39;&lt;input value=&quot;&#39; + csv[2] + &#39;&quot; name=&quot;in-time&quot; type=&quot;hidden&quot;&gt;&#39;;
  out += &#39;&lt;input value=&quot;&#39; + csv[3] + &#39;&quot; name=&quot;out-time&quot; type=&quot;hidden&quot;&gt;&#39;;

  document.getElementById(&#39;csvForm&#39;).innerHTML = out;
  document.getElementById(&#39;csvForm&#39;).setAttribute(&quot;formmethod&quot;, &quot;post&quot;);
  document.getElementById(&#39;csvForm&#39;).setAttribute(&quot;formaction&quot;, &quot;testBrain.jsp&quot;);
  out += &#39;&lt;br&gt;&#39;;
}

<!-- language: lang-html -->

&lt;input id=&quot;upload&quot; type=&quot;file&quot;&gt;

&lt;form id=&quot;csvForm&quot;&gt;&lt;/form&gt;
&lt;input type=&quot;submit&quot; value=&quot;submit&quot; form=&quot;csvForm&quot; formmethod=&quot;post&quot; formaction=&quot;testBrain.jsp&quot;&gt;

&lt;script src=&quot;https://d3js.org/d3.v3.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

testBrain.jsp

&lt;%@ page contentType=&quot;text/html;charset=UTF-8&quot; language=&quot;java&quot; %&gt;
&lt;%@page import=&quot;java.sql.*,java.util.*&quot;%&gt;

&lt;html&gt;
&lt;head&gt;
    &lt;meta http-equiv=&quot;Refresh&quot; content=&quot;5;url=test.jsp&quot;&gt;
&lt;/head&gt;
&lt;/html&gt;
&lt;%
    String[] date=request.getParameterValues(&quot;date&quot;);
    String[] name=request.getParameterValues(&quot;name&quot;);
    String[] inTime=request.getParameterValues(&quot;in-time&quot;);
    String[] outTime=request.getParameterValues(&quot;out-time&quot;);

    try
    {
        Class.forName(&quot;com.mysql.jdbc.Driver&quot;);
        Connection conn = DriverManager.getConnection(&quot;jdbc:mysql://localhost:3306/testDb&quot;, &quot;root&quot;, &quot;1234&quot;);
        Statement st=conn.createStatement();

        for(int x=0; x&lt;name.length;x++) {
            int i = st.executeUpdate(&quot;insert into csv(date,name,`in`,`out`)values(&#39;&quot; + date[x] + &quot;&#39;,&#39;&quot; + name[x] + &quot;&#39;,&#39;&quot; + inTime[x] + &quot;&#39;,&#39;&quot; + outTime[x] + &quot;&#39;)&quot;);
        }
        out.println(&quot;Data is successfully inserted! Redirecting.. Please wait&quot;);

       // String redirectURL = &quot;test.jsp&quot;;
       // response.sendRedirect(redirectURL);

    }
    catch(Exception e)
    {
        System.out.print(e);
        e.printStackTrace();
        out.println(&quot;Error&quot;);
    }
%&gt;

I used this question and changed some stuff for it to work.
You can view the content before submitting it by removing the &quot;type = hidden&quot; in the createForm JS.

huangapple
  • 本文由 发表于 2020年5月5日 20:35:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/61613293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定