我正在尝试使用以下代码
将CSV文件上传到mysqlMyjsp.jsp;
<form action="CSVFileUploadSERvlet" method="post">
<input type="file" name="file"><br>
<input type="submit" value="Submit">
</form>
CSVFileUploadSERvlet.java:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*String getPath = request.getParameter("file");
System.out.println(getPath);*/ //I know this return null
File filename1 =new File("/home/raptorjd4/Desktop/CheckingCSVFile.csv");
String tablename ="Checking_table";
String query=null;
PrintWriter obj1 = response.getWriter();
try {
if(filename1.exists())
{
conv = new Connectivity();
con = conv.setConnection();
st = con.createStatement();
query = "LOAD DATA LOCAL INFILE \"" + filename1 + "\" INTO TABLE " + tablename + " FIELDS TERMINATED BY ',' IGNORE 1 LINES";
st.executeUpdate(query);
obj1.println("Row (1) inserted");
}
else
{
obj1.println("File not found...!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
如果我直接提供文件路径File filename1 =new File("/home/raptorjd4/Desktop/CheckingCSVFile.csv");
,则文件上传到数据库成功。但是如何获取上传文件路径并执行此操作File filename1 =new File(UploadedFilePath);
。
有人更改我的代码以将csv文件上传到mysql。
答案 0 :(得分:0)
//in your jsp form tag add enctype="multipart/form-data" method="post"
//In servlet, you need to get content type first.
String contentType = request.getContentType();
//now this contentType contains multipart data
if (contentType.toLowerCase().contains("multipart")) {
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String data= null;
do {
// skip first header lines which contains the header data such as Content-Disposition or Content-Type
data = reader.readLine();
} while(!(data.toLowerCase().contains("content-type")));
while( (data = reader.readLine()) != null) {
if(data.startsWith("--")) {
continue;
}
if (!data.toLowerCase().contains("webkitformboundary")) {
if (!data.toLowerCase().contains("content-disposition")) {
System.out.println("+++++++++++++++++++ data: "+data);
}
}
}
}