我正在尝试一次上传多个csv文件,而上传错误即将到来。 下面我给了我的代码,我试过但是有一些问题就在那里。请任何人帮助我。
这是我的代码。
servlet.java
private static final String TMP_DIR_PATH = System.getProperty("user.home"); //= "/";
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "/";
private File destinationDir;
/**
*
* @param config
* @throws ServletException
*/
@Override
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);
if (!destinationDir.isDirectory()) {
System.out.println(realPath);
throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
}
}
/**
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@Override
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);
int check = 0, i = 0, j = 0, k = 0, l = 0;
String name1 = "";
String[] name11 = new String[100];
String name2 = "";
String[] name22 = new String[100];
String name3 = "";
String[] name33 = new String[100];
String filename = "";
String[] filename1 = new String[100];
File file[] = new File[50];
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext() && !itr.equals("")) {
FileItem item = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if (item.isFormField()) {
if (item.getFieldName().equals("text1")) {
name1 = item.getString();
name11[i] = name1;
System.out.println("name1=" + name1);
i++;
}
if (item.getFieldName().equals("text2")) {
name2 = item.getString();
name22[j] = name2;
System.out.println("name2=" + name2);
j++;
}
if (item.getFieldName().equals("text3")) {
name3 = item.getString();
name33[k] = name3;
System.out.println("name3=" + name3);
k++;
}
if (item.getFieldName().equals("check")) {
check = Integer.parseInt(item.getString());
System.out.println("check valu:" + check);
}
} else if(item.) {
//Handle Uploaded files.
out.println("Field Name = " + item.getFieldName()
+ ", File Name = " + item.getName()
+ ", Content type = " + item.getContentType()
+ ", File Size = " + item.getSize());
filename = item.getName();
filename1[l] = filename;
/*
* Write file to the ultimate location.
*/
file[l] = new File(destinationDir,filename1[l]);
item.write(file[l]);
l++;
}
}
request.setAttribute("name1", name11);
request.setAttribute("name2", name22);
request.setAttribute("name3", name33);
request.setAttribute("filename", filename1);
if (check == 7) {
RequestDispatcher dispatcher = request.getRequestDispatcher("dispatched.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);
}
} }
formcode.jsp
<form action="Commonsfileuploadservlet2" enctype="multipart/form-data" method="POST" name="form3">
<input type="hidden" name="check" value="7" />
<table align="center">
<th colspan="3" class="style30"><font size="5">Adding Programme</th>
</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 = 1; i < 6; i++) {
%>
<tr>
<td><input type="text" name="text1" size="11"> </td>
<td><input type="text" name="text2" size="10"> </td>
<td><input type="file" name="file1"></td>
</tr>
<%}%>
</table>
<table align="center">
<tr>
<td><input type="submit" name="submit" value="submit"></td>
<td><input type="button" name="add" value="Add"></td>
</tr>
</table>
</form>
dispatched.jsp
<%
Calendar now = Calendar.getInstance();
System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
+ "-"
+ now.get(Calendar.DATE)
+ "-"
+ now.get(Calendar.YEAR));
int cyear = now.get(Calendar.YEAR);
int i, len;
String[] pname = (String[]) request.getAttribute("name1");
String[] pcode = (String[]) request.getAttribute("name2");
String[] filename = (String[]) request.getAttribute("filename");
String pname1 = "";
Statement st1 = con.createStatement();
Statement st2 = con.createStatement();
Statement st3 = con.createStatement();
Statement st4 = con.createStatement();
Statement st5 = con.createStatement();
Statement st6 = con.createStatement();
try {
st1.executeUpdate("create table if not exists programme_table(pname varchar(200) NOT NULL ,pcode varchar(200)NOT NULL,primary key(pname))");
for (i = 0; i <=pname.length; i++) {
if (pname[i] == "" && pcode[i] == "" && filename[i] == "" && filename[i] == null) {
continue;
}
String realPath = getServletContext().getRealPath("/");
File f1 = new File(realPath + filename[i]);
File f2 = new File("/var/lib/mysql/dcis_attendance_system/" + filename[i]);
InputStream in = new FileInputStream(f1);
OutputStream out1 = new FileOutputStream(f2);
byte[] buf = new byte[1024];
while ((len = in.read(buf)) > 0) {
out1.write(buf, 0, len);
}
pname1 = pname[i];
pname1 = pname1.replace('-', '_');
st2.executeUpdate("insert into programme_table(pname,pcode)values('" + pname[i] + "','" + pcode[i] + "')");
st3.executeUpdate("create table if not exists " + pname1 + "_curriculumversions(year varchar(200) NOT NULL ,curriculumname varchar(200),primary key(year))");
st4.execute("insert into " + pname1 + "_curriculumversions(year,curriculumname)values('" + cyear + "','" + pname1 + "_" + cyear + "_curriculum')");
st5.executeUpdate("create table if not exists " + pname1 + "_" + cyear + "_curriculum(subjectid varchar(20),subjectname varchar(100),credits varchar(20),semester varchar(20),sno INT,primary key(sno)) ");
String qry2 = "LOAD DATA INFILE '" + filename[i] + "' INTO TABLE " + pname1 + "_" + cyear + "_curriculum FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' (subjectid,subjectname,credits,semester,sno)";
st6.executeUpdate(qry2);
}
} catch (Exception e) {
e.printStackTrace();
}
%>