首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

DWR入门 (4)文件上传

2013-12-10 
DWR入门 (四)文件上传DWR的文件上传有点繁琐,首先版本要使用3.0.RC2。据我了解,DWR的版本更新还是比较慢的。

DWR入门 (四)文件上传
DWR的文件上传有点繁琐,首先版本要使用3.0.RC2。
据我了解,DWR的版本更新还是比较慢的。 而且3.0.RC2没有被发布到maven中央服务器上,我们必须自己下载,加入本地仓库才能使用。
http://directwebremoting.org/dwr/downloads/index.html#maven


这个网址http://directwebremoting.org/jira/browse/DWR-331就是关于Chrome中DWR无法正常上传文件的具体错误信息以及解决方案。(其实IE也不行)


开始写代码。
首先在HelloDwr.java中加入以下代码:

public String upload(InputStream is, String filename){String fn=FilenameUtils.getName(filename);try {FileUtils.copyInputStreamToFile(is, new File("d:/"+fn));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return fn;}


然后写一个上传jsp页面:


<html><head><script src="http://code.jquery.com/jquery-1.9.0.js"></script><script type="text/javascript" src="<%=path%>/dwr/engine.js"></script><script type="text/javascript"src="<%=path%>/dwr/interface/HelloDwr.js"></script><script type="text/javascript">  $(function(){ $("#btn").on("click",upload);  });  function upload(){ var f=$("#uf"); var f2=document.getElementById("uf"); //alert(f); //alert(f.val()); console.log(f); HelloDwr.upload(f2,f2.value,function(data){ alert(data); });    }</script></head><body> <input type="file" id="uf"/><input id="btn" type="button" value="上传"/></body></html>



关于错误信息
1.如果dwr版本不正确,console会报错Cannot set property 'batch' of null
google查询便会找到上面那个官方的Issue网址。

2. 如果没有加入commons.fileupload依赖包,便会报错:
警告: Exception while processing batch
java.lang.UnsupportedOperationException: File uploads not supported
at org.directwebremoting.dwrp.UnsupportedFileUpload.parseRequest(UnsupportedFileUpload.java:41)
at org.directwebremoting.d wrp.Batch.parsePost(Batch.java:135)
at org.directwebremoting.dwrp.Batch.<init>(Batch.java:58)
at org.directwebremoting.dwrp.CallBatch.<init>(CallBatch.java:46)
at org.directwebremoting.dwrp.BaseCallHandler.handle(BaseCallHandler.java:74)
at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:120)
at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:141)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:575)





=========================
补充:
如果想把文件放入项目目录下,可以修改upload方法:

public String upload(InputStream is, String filename){WebContext wc=WebContextFactory.get();HttpServletRequest req=wc.getHttpServletRequest();//这里可以将上传文件放入webapp/img目录中.String realPath=req.getSession().getServletContext().getRealPath("/img");System.out.println("realpath= "+realPath);String fn=FilenameUtils.getName(filename);try {FileUtils.copyInputStreamToFile(is, new File(realPath+fn));} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return fn;}

运行之后,在myeclipse的webapp目录点刷新,便可看到上传文件。

热点排行