对于实现文件上传功能来说,Commons-fileupload组件是一个不错的选择,本文使用它实现了单个文件及多个文件上传,这里将实现过程写出来与大家共享。
1.单个文件上传。
页面代码:
....<div id="content">
<fieldset><legend>下載列表</legend>
<ul>
<%
List<String> downloadList=(List<String>)request.getAttribute("downloadList");
if(downloadList!=null){
for(String str:downloadList){
out.print("<li><a href='DownloadFile?file="+str+"'>"+str+"</a></li>");
}
}
%>
</ul>
</fieldset>
<!-- enctype属性为表单定义了MIME编码方式,上传文件的表单enctype属性必须如此设置 -->
<form method="post" action="UploadFile" enctype="multipart/form-data" >
<p><input type="text" name="fileIntro" value="" />文件介绍</p>
<p><input type="file" name="myfile1" value="浏览文件" /></p>
<p><input type="submit" value="上传"/></p>
</form>
</div>....
在上传表单中,既有普通文本域也有文件上传域,注意在Servlet中取它们和平常的做法不同:
Servlet代码:
package com.sitinspring.action;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.sitinspring.util.UploadUtil;
/**
* 用于文件上传处理的Servlet
* @author sitinspring
*
* @date 2008-2-12
*/
public class UploadFileServlet extends HttpServlet {
private static final long serialVersionUID = 56890894234786L;
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
request.setCharacterEncoding("UTF-8");
// 文件上傳部分
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart == true) {
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// 得到所有的表单域,它们目前都被当作FileItem
List<FileItem> fileItems = upload.parseRequest(request);
Iterator<FileItem> iter = fileItems.iterator();
// 依次处理每个表单域
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if(item.isFormField()){
// 如果item是正常的表单域
String name = item.getFieldName();
String value = item.getString();
System.out.print("表单域名为:"+name+"表单域值为:"+value);
}
else{
// 如果item是文件上传表单域
// 获得文件名及路径
String fileName = item.getName();
if (fileName != null) {
File fullFile = new File(item.getName());
// 如果文件存在则上传
if(fullFile.exists()){
File fileOnServer = new File(UploadUtil.getUploadPath(),
fullFile.getName());
item.write(fileOnServer);
System.out.println("文件"+fileOnServer.getName()+"上传成功");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("the enctype must be multipart/form-data");
}
// 取得服务器中已有文件的下載列表
List<String> fileListInServer=new ArrayList<String>();
File dir = new File(UploadUtil.getUploadPath());
String[] children = dir.list();
if (children != null) {
for (int i=0; i<children.length; i++) {
fileListInServer.add(children[i]);
}
}
request.setAttribute("downloadList", fileListInServer);
// 跳回原頁面
RequestDispatcher dispatcher = request
.getRequestDispatcher("/web/page/uploadtoserver.jsp");
dispatcher.forward(request, response);
return;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
doPost(request, response);
}
}
从上面的代码可以看出,无论是否文件上传表单域都被当成了FileItem来处理,要区别开来使用isFormField()方法即可,返回真是常规表单域,返回假则是文件上传表单域。
2.多个文件上传到服务器端。
这里采用JS动态生成几个文件上传表单域即可,Servlet无需改变。
多文件上传页面代码如下:
<%@ page contentType="text/html; charset=UTF-8"%>
<%@page language="java" import="java.util.List"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>上传多個文件到服务器</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" rev="stylesheet" href="web/css/style.css"
type="text/css" />
</head>
<body>
<div id="bodyDiv">
<div id="header">
<jsp:include page="/web/page/branch/header.jsp"/>
</div>
<div id="sidebar">
<jsp:include page="/web/page/branch/sidebar.jsp"/>
</div>
<div id="content">
<fieldset><legend>下載列表</legend>
<ul>
<%
List<String> downloadList=(List<String>)request.getAttribute("downloadList");
if(downloadList!=null){
for(String str:downloadList){
out.print("<li><a href='DownloadFile?file="+str+"'>"+str+"</a></li>");
}
}
%>
</ul>
</fieldset>
<!-- enctype属性为表单定义了MIME编码方式,上传文件的表单enctype属性必须如此设置 -->
<form name="uploadForm" method="post" action="UploadFile" enctype="multipart/form-data" >
<p><input type="button" value="增加上传按钮" onclick="addUploadButton()"/></p>
<p><input type="file" name="myfile1" value="浏览文件" /></p>
<p><input type="submit" value="上传"/></p>
</form>
</div>
<div id="footer">
<jsp:include page="/web/page/branch/footer.jsp"/>
</div>
</div>
</body>
JS代码:
<script LANGUAGE="JavaScript">
<!--
var count=1;
function addUploadButton(){
// 按ID找到FOrm
var uploadForm=document.getElementById("uploadForm");
// 创建P元素
var pNode=document.createElement("p");
// 累加Count以观察次数
count=count+1;
pNode.innerHTML="<input type='file' name='myfile"+count+"' value='浏览文件'/>";
// 将P元素添加到body中
uploadForm.appendChild(pNode);
}
//-->
</script>
</html>
实例代码:
http://www.blogjava.net/Files/sitinspring/FileUpload20080412145412.rar