java操作檔案批量上傳
package com.fangdi.landaudit.process.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
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 UploadFile extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public UploadFile() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 建立檔案處理工廠,它用於生成FileItem物件。
DiskFileItemFactory difactory = new DiskFileItemFactory();
// 設定快取大小,如果上傳檔案超過快取大小,將使用臨時目錄做為快取。
difactory.setSizeThreshold(1024 * 1024);
// 設定處理工廠快取的臨時目錄,此目錄下的檔案需要手動刪除。
String dir = this.getServletContext().getRealPath("/");
File filedir = new File(dir + "filetemp");
if (!filedir.exists())
filedir.mkdir();
difactory.setRepository(filedir);
// 設定檔案實際儲存的目錄
String userdir = dir + "files";
File fudir = new File(userdir);
if (!fudir.exists())
fudir.mkdir();
// 建立request的解析器,它會將資料封裝到FileItem物件中。
ServletFileUpload sfu = new ServletFileUpload(difactory);
sfu.setHeaderEncoding("utf-8");
// 解析儲存在request中的資料並返回list集合
List list = null;
try {
list = sfu.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
// 遍歷list集合,取出每一個輸入項的FileItem物件,並分別獲取資料
for (Iterator it = list.iterator(); it.hasNext();) {
FileItem fi = (FileItem) it.next();
if (fi.isFormField()) {
System.out.println(fi.getFieldName());
System.out.println(fi.getString());
} else {
// 由於客戶端向伺服器傳送的檔案是客戶端的全路徑,在這我們只需要檔名即可
String filename = fi.getName();
int index = filename.lastIndexOf("\\");
if (index != -1){
filename = filename.substring(index + 1);
// 向伺服器寫出檔案
InputStream in = fi.getInputStream();
FileOutputStream fos = new FileOutputStream(fudir + "/"
+ filename);
byte[] buf = new byte[1024];
int len = -1;
while ((len = in.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 關閉流
if (in != null) {
try {
in.close();
} finally {
if (fos != null)
fos.close();
}
}
}
}
}
}
public void init() throws ServletException {
// Put your code here
}
}
頁面
<body topmargin="0" leftmargin="0" rightmargin="0" marginheight="0" marginwidth="0">
<form name="form2" enctype="multipart/form-data" method="post" action="<%=path%>/servlet/UploadFile">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td><b>請選擇上傳的檔案:</b>
<input id="file" name="file" type="file" size="35"><input type="button" value="新增" onclick="addRow()">
</td>
</tr>
<tr style="display: none;" id="myTr">
<td><b>請選擇上傳的檔案:</b>
<input id="file" name="file" type="file" size="35"><input type="button" value="刪除" onclick="delRow(this)">
</td>
</tr>
</table>
<input name="Submit" type="submit" class="btn_grey" value="確認">
<input name="Submit2" type="button" class="btn_grey" onClick="window.close()" value="關閉">
</form>
</body>
<script type="text/javascript">
function addRow()
{
var tr = document.getElementById("myTr");
var con = tr.cloneNode(true);
con.removeAttribute("style");
tr.parentNode.insertAdjacentElement("beforeEnd",con);
}
function delRow(obj)
{
var tr=obj.parentNode.parentNode;
tr.parentNode.removeChild(tr);
}
</script>