public class MyDwr {

/**

     * 文件上传

     * @return

     * @throws IOException

     */

    public String upload(InputStream is ,String filename) throws IOException{
    //通过dwr提供的这个方法来获得webContext
    //而这个对象可以获取HttpServlet的对象
    WebContext wc = WebContextFactory.get();
    HttpServletRequest req = wc.getHttpServletRequest();
    String realPath = req.getSession().getServletContext().getRealPath("upload");
  
    System.out.println(filename);
    //获取文件的文件名,这个获取的文件名对各个浏览器是没有差异的
    String fn = FilenameUtils.getName(filename);
    System.out.println(fn);
   //  String lastName = fn.substring(fn.lastIndexOf("/")+1,fn.length());
   //  System.out.println(lastName);
    String filePath = realPath+"/"+fn;
    System.out.println(filePath);
    //生成新的文件
    FileUtils.copyInputStreamToFile(is, new File(filePath));
    return filePath;
  
   }

}

 

 

<html>

  <head>

    <title>ch11-dwr</title>

   

    <script type="text/javascript" src="/dwr-first/dwr/engine.js"></script>

    <script type="text/javascript" src="/dwr-first/dwr/util.js"> </script>

    <script type="text/javascript" src="/dwr-first/dwr/interface/MyDwr.js"></script>

    <script type="text/javascript">

       function upload(){

           var file = dwr.util.getValue("myfile");

        //file对象的value值是这个file的路径不同的浏览器路径字符串不同
        alert(file.value);
        //一个输入流对象

           alert(file);

           MyDwr.upload(file,file.value,function(data){

              alert(data);

           });

       }

    </script>

  </head>

  <body>

  <input type="file" id="myfile"/>

    <input type="button" value="上传文件" onclick="upload()"/>

  </body>

</html>