項目結構圖
javascript
加入所需的 jar 包。html
commons-logging-1.1.1.jarjava
dwr.jarweb
這兩個是 dwr 環境所必須的。apache
commons-fileupload-1.3.1.jarapp
commons-io-2.4.jarjsp
這兩個是上次文件所必須的。url
web.xml 配置 dwrspa
<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.net
package com.service; 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.WebContext; import org.directwebremoting.WebContextFactory; public class Upload { public String upload(InputStream is, String fileName) throws IOException{ //dwr經過WebContext取得HttpServletRequest WebContext wc = WebContextFactory.get(); HttpServletRequest req = wc.getHttpServletRequest(); String realpath = req.getSession().getServletContext().getRealPath("upload");//獲取根目錄下upload文件下路徑 String fn = FilenameUtils.getName(fileName);//獲取上傳的文件的名稱 String filepath = realpath + "/" + fn;//文件上傳存放的路徑 FileUtils.copyInputStreamToFile(is, new File(filepath));//將輸入流直接copy成文件 return filepath; } }
3. 建立 dwr.xml ,配置 Upload.java 映射
<dwr> <allow> <create creator="new" javascript="Upload"> <param name="class" value="com.service.Upload" /> </create> </allow> </dwr>
4. 建立 upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>dwr上傳文件</title> </head> <script type='text/javascript' src='dwr/engine.js'></script> <script type='text/javascript' src='dwr/util.js'></script> <script type="text/javascript" src="dwr/interface/Upload.js"></script> <script type="text/javascript"> function upload(){ var file = dwr.util.getValue("myfile"); Upload.upload(file,file.value,function(data){ alert(data); }); } </script> <body> <input type="file" id="myfile"/> <input type="button" value="上傳" onclick="upload();"/> </body> </html>
upload.jsp 中,須要引入
<script type='text/javascript' src='dwr/engine.js'></script> <script type='text/javascript' src='dwr/util.js'></script> <script type="text/javascript" src="dwr/interface/Upload.js"></script>
其中
<script type="text/javascript" src="dwr/interface/Upload.js"></script>
是咱們配置的 Upload.java
直接 Upload.upload(file,fileName); 便可調用 Upload.java 中的 upload 方法執行上傳操做。
上傳成功後,能夠到部署路徑下upload文件夾下查看所上傳的文件。
有須要源碼的:源碼