不用自己写了,源码可以从
http://www.telio.be/blog/2006/01/06/ajax-upload-progress-monitor-for-commons-fileupload-example里面下载,
下载地址
http://www.telio.be/blog/wp-content/uploads/2006/01/ajax-upload-1.0.war
下载完之后,你需要解包,在命令行中:
jar xvf ajax-upload-1.0.war
源码就在\WEB-INF\src下面
将要用到的文件有resources文件夹下,\WEB-INF\下面的dwr.xml和lib下面的jar文件
上传页面
在上面解开的包里面有index.jsp这个是上传页面,upload.jsp负责上传,resources包里面包含了dwr与服务器通讯的javascript脚本,你需要把index.jsp的form中的action换成你的struts action即可,然后把form中的file名改成你actionform中的file属性名,把页面中剩余的file去掉
index.jsp上传页面示例代码:
<%@ page contentType="text/html; charset=gb2312" language="java"
import="java.util.*" errorPage=""%>
<%
String path=request.getContextPath();
%>
<html locale="true">
<head>
<SCRIPT language=javascript>
function check_file() {
var strFileName=document.forms(0).file;
if (strFileName.value==""){
alert("请选择要上传的文件");
return false;
}
startProgress();
}
function loadmessage(){
<%
if (request.getAttribute("message") != null) {
%>
window.alert("<%=request.getAttribute("message")%>");
window.returnValue="yes";
<%}%>
}
</SCRIPT>
<title>上传</title>
<script src='<%=path%>/resources/js/upload.js'></script>
<script src='<%=path%>/dwr/interface/UploadMonitor.js'></script>
<script src='<%=path%>/dwr/engine.js'></script>
<script src='<%=path%>/dwr/util.js'></script>
<style type="text/css">
#progressBar { padding-top: 5px; }
#progressBarBox { width: 350px; height: 20px; border: 1px inset; background: #eee;}
#progressBarBoxContent { width: 0; height: 20px; border-right: 1px solid #444; background: blue; }
</style>
<LINK href="<%=path%>/css/style.css"type="text/css" rel="stylesheet">
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<style type="text/css">
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
-->
</style>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onLoad="loadmessage()">
<form name="form" method="post" action="<%=path%>/upload.do?method=upload"enctype="multipart/form-data" onSubmit="return check_file()">
<table width="60%" border="0" cellspacing="1">
<tr background-color=" #E7F5FE">
<td width="30%" align="right">从文件导入:</td>
<td width="51%"><input type="file" name="file" class="input"></td>
<td width="27%"><input type="submit" name="files" class="button_4"
style="border-style:None;width:71px;" value="确定" id="uploadbutton">
</td>
</tr>
<tr align="left" background-color=" #E7F5FE">
<td colspan="3">
<div id="progressBar" style="display: none;">
<div id="theMeter">
<div id="progressBarText"></div>
<div id="progressBarBox">
<div id="progressBarBoxContent"></div>
</div>
</div>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
并且要修改一下\resources\js中的upload.js文件:
/* Licence:
* Use this however/wherever you like, just don't blame me if it breaks anything.
*
* Credit:
* If you're nice, you'll leave this bit:
*
* Class by Pierre-Alexandre Losson -- http://www.telio.be/blog
* email : plosson@users.sourceforge.net
*/
function refreshProgress()
{
UploadMonitor.getUploadInfo(updateProgress);
}
function updateProgress(uploadInfo)
{
if (uploadInfo.inProgress)
{
document.getElementById('uploadbutton').disabled = true;
document.getElementById('file').disabled = true;
var fileIndex = uploadInfo.fileIndex;
var progressPercent = Math.ceil((uploadInfo.bytesRead / uploadInfo.totalSize) * 100);
document.getElementById('progressBarText').innerHTML = '文件读取进度: ' + progressPercent + '%';
document.getElementById('progressBarBoxContent').style.width = parseInt(progressPercent * 3.5) + 'px';
window.setTimeout('refreshProgress()', 1000);
}
else
{
document.getElementById('uploadbutton').disabled = false;
document.getElementById('file').disabled = false;
}
return true;
}
function startProgress()
{
document.getElementById('progressBar').style.display = 'block';
document.getElementById('progressBarText').innerHTML = '文件读取进度: 0%';
document.getElementById('uploadbutton').disabled = true;
// wait a little while to make sure the upload has started ..
window.setTimeout("refreshProgress()", 1000);
return true;
}
配置dwr.xml
放在/WEB-INF/下面
<dwr>
<allow>
<create creator="new" javascript="UploadMonitor">
<param name="class" value="be.telio.mediastore.ui.upload.UploadMonitor"/>
</create>
<convert converter="bean" match="be.telio.mediastore.ui.upload.UploadInfo"/>
</allow>
</dwr>
web.xml中配置dwr,省略spring,struts等的配置
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR Servlet</display-name>
<servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>logLevel</param-name>
<param-value>WARN</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
编写struts的MultipartRequestHandler :AjaxMultipartRequestHandler
实现 MultipartRequestHandler接口并在struts-config.xml的controller中替换默认的multipartClass
<controller>
<set-property property="multipartClass"
value="org.springside.components.ajaxupload.AjaxMultipartRequestHandler" />
</controller>
其实这个类AjaxMultipartRequestHandler编写很简单,把struts的src源码中的org.apache.struts.upload.CommonsMultipartRequestHandler.java修改一下就可以了:
在publicvoid handleRequest(HttpServletRequest request)
throws ServletException {
方法中把定义factory之前的那几行代码注释掉然后写入
UploadListener listener = new UploadListener(request, 30);
FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
之后再注释掉
// upload.setSizeThreshold((int) getSizeThreshold(ac));
// upload.setRepositoryPath(getRepositoryPath(ac));
这个类就算写完了
编写struts上传类
就用你原来编写的struts上传类
上传方法代码段示例:
/**
*上传文件
*/
public ActionForward upload(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String path = getServlet().getServletContext().getRealPath("/");
log.info(">>>>>>>>>>>>>>>path:" + path);
if (form == null) {
return mapping.findForward("success");
}
FileUploadForm fuf = (FileUploadForm) form;
FormFile file = fuf.getFile();
try {
if (file == null) {
log.info(">>>>>>>>>>>>>>>file为空");
return mapping.findForward("success");
}
} catch (Exception e) {
e.printStackTrace();
}
String fname = file.getFileName();
int t = 0;
for (int i = 0; i < fname.length(); i++) {
if (fname.charAt(i) == '.') {
t = i;
}
}
String filename = null;
if (t > 0) {
filename = fname.substring(0, t);
}
log.info(">>>>>>>>>>>>>>>文件名:" + filename);
String filepath = path + "dataimport/upfiles/" + fname;
File f = new File(path + "dataimport/upfiles/");
log.info(">>>>>>>>>>>>>>>文件生成路径:" + filepath);
if (!f.exists()) {
f.mkdirs();
} else {
log.info(">>>>>>>>>>>>>>>路径存在");
}
InputStream stream = file.getInputStream();
OutputStream os = new FileOutputStream(path + "dataimport/upfiles/"
+ fname);
int readBytes = 0;
byte buffer[] = newbyte[8192];
while ((readBytes = stream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, readBytes);
}
os.close();
stream.close();
file.destroy();
String message = "成功!";
request.setAttribute("message", message);
returnmapping.findForward("success");
}
分享到:
相关推荐
采用dwr+Ajax和struts开发文件上传进度条(网络文章)
### Struts 1.2 下实现文件上传进度条的关键知识点 #### 一、背景与目的 在基于Struts 1.2的Web应用中,实现文件上传时常常需要提供一个友好的用户界面来显示文件上传进度。这不仅提高了用户体验,还能够实时反馈...
本文将深入探讨如何使用DWR(Direct Web Remoting)和Struts框架实现文件上传进度条功能。 ### DWR:Direct Web Remoting DWR是一种开源技术,它简化了Java与JavaScript之间的远程调用过程,使得在Web应用中使用...
"fileupload+dwr2+webwork2实现带进度条上传文件"这个主题涉及到三个关键技术和组件:FileUpload、Direct Web Remoting (DWR) 和 WebWork2,它们协同工作以提供一个带有进度条的高效、用户友好的文件上传体验。...
Struts2和DWR是两种在Web开发中广泛使用的开源框架,它们分别处理不同的层面,但可以协同工作以实现高效的应用程序开发。Struts2是一个强大的MVC(Model-View-Controller)框架,用于构建Java Web应用程序,而Direct...
Struts2-DWR带进度条文件上传是一种在Web应用程序中实现大文件上传并显示实时进度条的技术组合。Struts2是一个流行的Java MVC框架,用于构建企业级Web应用,而DWR(Direct Web Remoting)是一个JavaScript库,允许在...
标题中的"uploadify3.0 strut2 dwr3整合例子"指的是一个基于Web开发的示例项目,它结合了三个关键的技术组件:Uploadify 3.0、Struts2和DWR3。这个项目旨在展示如何在实际应用中有效地集成这些工具,以便实现文件...
- AjaxUpload:实现文件上传过程中的进度条显示。 - **后端技术**: - Acegi/Spring Security:提供强大的认证授权机制。 - Hibernate:ORM框架,简化数据库访问操作。 - ExtremeTable:表格控件,用于数据展示...
此插件支持两套主流的AJAX框架:EXT2和DWR框架的快速导入,从而使得开发者能够快速集成AJAX功能到自己的项目中,提升页面的响应速度和交互性。 #### 4. HTML在线编辑器一键导入功能 在进行Web前端开发时,HTML在线...
Beta1:基本功能 2008年3月,4月开发出雏形 v1.0 2008年5月修正了SSH不能可视化编辑struts-config.xml文件的问题,优化了进度条显示问题。 2008年6月修正了生成自定义MVC框架时的包名不能自定义的bug...