这里需要用到commons-fileupload-1.2.2和commons-io-2.3
This is the web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>dwr-invoker</servlet-name> <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class> <!-- 配置debug参数为true后,就可以访问DWR的控制台了,访问地址为 http://ip:port/webApp/dwr/ --> <!-- 开发阶段可以开启控制台,但在产品交付时,务必关掉控制台 --> <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> </web-app>
This is DWR Config File----dwr.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 3.0//EN" "http://getahead.org/dwr/dwr30.dtd"> <dwr> <allow> <create creator="new" javascript="JSUserManager"> <param name="class" value="com.jadyer.dwr.UserManager" /> </create> </allow> </dwr>
下面是用于提交上传操作的前台页面upload.jsp
<%@ page language="java" pageEncoding="UTF-8"%> <script type="text/javascript" src="<%=request.getContextPath ()%>/dwr/interface/JSUserManager.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script> <script type="text/javascript" src="<%=request.getContextPath()%>/dwr/util.js"></script> <script type="text/javascript"> function upload() { var file = dwr.util.getValue("myfile"); alert(file.value);//不同浏览器在此处得到的值,不一定相同....IE9得到的是含全 路径的文件名,firefox12得到的是文件名 alert(file); JSUserManager.upload(file, file.value, function(data){ alert(data); }); } </script> <input type="file" id="myfile"/> <input type="button" value="上传文件" onclick="upload()"/>
import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.directwebremoting.WebContextFactory; public class UserManager { /** * 上传文件 * @param is DWR会自动把dwr.util.getValue("myfile")转换为这里所需的 InputStream * @param filename 不同浏览器传进来的值未必相同,IE9传是含全路径的文件名,firefox12 传的是文件名 * @return 文件的真实名字 */ public String upload(InputStream is, String filename) throws IOException{ String realname = FilenameUtils.getName(filename); //获取文件的真实名字 HttpServletRequest request = WebContextFactory.get().getHttpServletRequest (); //获取Servlet API String realpath = request.getSession().getServletContext().getRealPath ("/WEB-INF/upload"); FileUtils.copyInputStreamToFile(is, new File(realpath, realname)); return realname; } }
补充:记得建立//WEB-INF//upload//
目录,其用于接收所上传的文件