效果:
首先配置好DWR环境,可以参考我上一篇文章http://blog.csdn.net/javer_lo/article/details/50038355
还需要在pom.xml中导入文件上传相应的依赖包,可以在这里找到所需的依赖包http://mvnrepository.com/
所有的依赖包如下:
<dependencies>
<dependency>
<groupId>org.directwebremoting</groupId>
<artifactId>dwr</artifactId>
<version>3.0.0-RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
</dependencies>
在HelloDwr类中增加以下方法:
public class HelloDwr {
public String upload(InputStream is, String fileName) throws IOException {
//获取相应的ServletAPI
WebContext wc = WebContextFactory.get();
//对应需要在webapp目录下创建upload文件夹
String realPath = wc.getSession().getServletContext().getRealPath("/upload");
String fn = FilenameUtils.getName(fileName);
File f = new File(realPath+"/"+fn);
//最终储存文件位置/dwr-hello/src/main/webapp/upload/xxx.type
//以下方法可以直接将输入流转换为文件
FileUtils.copyInputStreamToFile(is, f);
return fn;
}
}
在jsp页面中同样需要导入:
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/engine.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/HelloDwr.js"></script>
页面需要一个上传的按钮
<div style="width:45%;border:1px solid red">
<div class="form-group">
<label for="inputFile">File input</label>
<input id="uf" type="file">
</div>
<button id="btn" type="submit" class="btn btn-primary">Upload</button>
</div>
调用上传方法的JavaScript脚本:
$(function(){
$("#btn").click(function(){
var f = $("#uf").get(0);
var ff = $("#uf");
//ff[0]==f; ff.val()==f.value 这里随便注意一下js中的这些区别
print("f:"+f+"; f.value:"+f.value+" ;==ff:"+ff[0]+" ;ff.val()"+ff.val());
//var ff = document.getElementById("uf");
//HelloDwr.upload函数接受两个参数,第一个输入流f,第二个文件名f.value
HelloDwr.upload(f,f.value,function(data){
print("<br>["+data+"]<br>");
});
});
刷新后文件已经上传到upload文件夹下