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;}
<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>
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;}