项目结构图
加入所需的 jar 包。
commons-logging-1.1.1.jar
dwr.jar
这两个是 dwr 环境所必须的。
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
这两个是上次文件所必须的。
web.xml 配置 dwr
<servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class> org.directwebremoting.servlet.DwrServlet </servlet-class> <init-param> <param-name>debug</param-name> <param-value>true</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dwr-invoker</servlet-name> <url-pattern>/dwr/*</url-pattern> </servlet-mapping>
2. 创建 Upload.java
packagecom.service; importjava.io.File; importjava.io.IOException; importjava.io.InputStream; importjavax.servlet.http.HttpServletRequest; importorg.apache.commons.io.FileUtils; importorg.apache.commons.io.FilenameUtils; importorg.directwebremoting.WebContext; importorg.directwebremoting.WebContextFactory; publicclassUpload{ publicStringupload(InputStreamis,StringfileName)throwsIOException{ //dwr通过WebContext取得HttpServletRequest WebContextwc=WebContextFactory.get(); HttpServletRequestreq=wc.getHttpServletRequest(); Stringrealpath=req.getSession().getServletContext().getRealPath("upload");//获取根目录下upload文件下路径 Stringfn=FilenameUtils.getName(fileName);//获取上传的文件的名称 Stringfilepath=realpath+"/"+fn;//文件上传存放的路径 FileUtils.copyInputStreamToFile(is,newFile(filepath));//将输入流直接copy成文件 returnfilepath; } }
3. 创建 dwr.xml,配置 Upload.java 映射
<dwr> <allow> <createcreator="new"javascript="Upload"> <paramname="class"value="com.service.Upload"/> </create> </allow> </dwr>
4. 创建upload.jsp
<%@pagelanguage="java"import="java.util.*"pageEncoding="utf-8"%> <% Stringpath=request.getContextPath(); StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <basehref="<%=basePath%>"> <title>dwr上传文件</title> </head> <scripttype='text/javascript'src='dwr/engine.js'></script> <scripttype='text/javascript'src='dwr/util.js'></script> <scripttype="text/javascript"src="dwr/interface/Upload.js"></script> <scripttype="text/javascript"> functionupload(){ varfile=dwr.util.getValue("myfile"); Upload.upload(file,file.value,function(data){ alert(data); }); } </script> <body> <inputtype="file"id="myfile"/> <inputtype="button"value="上传"onclick="upload();"/> </body> </html>
upload.jsp 中,需要引入
<scripttype='text/javascript'src='dwr/engine.js'></script> <scripttype='text/javascript'src='dwr/util.js'></script> <scripttype="text/javascript"src="dwr/interface/Upload.js"></script>
其中
<scripttype="text/javascript"src="dwr/interface/Upload.js"></script>
是我们配置的 Upload.java
直接Upload.upload(file,fileName); 即可调用Upload.java 中的 upload 方法执行上传操作。
上传成功后,可以到部署路径下upload文件夹下查看所上传的文件。
有需要源码的:源码