DWR无刷新文件上传简单实例

效果:
最终文件上传结果
首先配置好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文件夹下
项目结构

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值