1.首先下载需要的.jar包:
commons-fileupload-1.1.jar
commons-io-1.1.jar
commons-logging.jar
dwr.jar
xiaole-upload.jar
2.配置web.xml文件
3.配置dwr.xml文件
"-//GetAhead Limited//DTD Direct Web Remoting
2.0//EN"
"http://getahead.org/dwr/dwr20.dtd">
4.编写index.jsp文件
<%@ page cOntentType="text/html;charset=UTF-8" language="java"
%>
<%
String path = request.getContextPath();
%>
My_AJAX_UpLoad/upload.do" enctype="multipart/form-data" method="post"
Onsubmit="startProgress()">
Web
upload
5.编写upload.js文件
function refreshProgress()
{
UploadMonitor.getUploadInfo(updateProgress);
}
function updateProgress(uploadInfo)
{
if (uploadInfo.inProgress)
{
document.getElementById('uploadbutton').disabled = true;
document.getElementById('file1').disabled = true;
document.getElementById('file2').disabled = true;
var progressPercent = Math.ceil((uploadInfo.bytesRead / uploadInfo.totalSize) * 100);
document.getElementById('progressBarText').innerHTML = 'upload in progress: ' + progressPercent + '%';
document.getElementById('progressBarBoxContent').style.width = parseInt(progressPercent * 3.5) + 'px';
window.setTimeout('refreshProgress()', 1000);
}
else
{
document.getElementById('uploadbutton').disabled = false;
document.getElementById('file1').disabled = false;
document.getElementById('file2').disabled = false;
}
return true;
}
function startProgress()
{
document.getElementById('progressBar').style.display = 'block';
document.getElementById('progressBarText').innerHTML = 'upload in
progress: 0%';
document.getElementById('uploadbutton').disabled
= true;
// wait a little while to make sure the
upload has started ..
window.setTimeout("refreshProgress()",
1500);
return true;
}
6.编写AjaxUploadTest.java文件
package upload;
import com.xiaole.upload.*;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
public class AjaxUploadTest extends HttpServlet {
private static final long serialVersiOnUID=
-7510933967709667319L;
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
HashMap hm = new HashMap();
hm.put(1, "txt,doc");
hm.put(2, "mp3");
AjaxUpload au = new AjaxUpload(request,
getServletContext().getRealPath("/") +
"tmp",
//这里设置的是临时路径
getServletContext().getRealPath("/") +
"upload", //这里是实际路径
-1,
//这里是上传的大小,-1为不限
hm);
try {
au.upload();
} catch (IsNotMulipartContentException inmce) {
inmce.printStackTrace(); // 不是multipart的表单数据
} catch (SizeLimitExceededException slee) {
slee.printStackTrace(); // 超过上传大小的限制
System.out.println("超过上传大小的限制");
} catch (InvalidPostfixException ipe) {
ipe.printStackTrace();
System.out.println("不合法的后缀");
} catch (Exception e) {
e.printStackTrace();
}
}
}