• DWR第五篇之文件上传


    1. 在第一篇架构基础上进行

    2. 修改maven依赖

     1 <dependencies>
     2     <dependency>
     3         <groupId>org.directwebremoting</groupId>
     4       <artifactId>dwr</artifactId>
     5       <version>3.0.1-RELEASE</version>
     6     </dependency>
     7     <dependency>
     8       <groupId>commons-logging</groupId>
     9       <artifactId>commons-logging</artifactId>
    10       <version>1.2</version>
    11     </dependency>
    12     <dependency>
    13         <groupId>commons-fileupload</groupId>
    14         <artifactId>commons-fileupload</artifactId>
    15         <version>1.3.1</version>
    16     </dependency>
    17     <dependency>
    18         <groupId>commons-io</groupId>
    19         <artifactId>commons-io</artifactId>
    20         <version>2.4</version>
    21     </dependency>
    22 </dependencies>

    3. 编写jsp页面

     1 <html>
     2 <head>
     3 <base href="<%=basePath%>">
     4 
     5 <title>dwr</title>
     6 <script type='text/javascript' src='dwr/engine.js'></script>
     7 <script type='text/javascript' src='dwr/util.js'></script>
     8 <script type='text/javascript' src='dwr/interface/CoreServlet.js'></script>
     9 </head>
    10 <body>
    11 
    12     <input type="file" name="file" />
    13     <button onclick="upload();">上传</button>
    14 
    15 </body>
    16 <script type="text/javascript">
    17     function upload() {
    18         var file = dwr.util.getValue("file");  
    19         CoreServlet.uploadFile(file, file.value, function(data) {
    20             if (data == true) {
    21                 alert("上传成功!");
    22             }
    23         });
    24     }
    25 </script>
    26 </html>

    4. 编写后台代码:

     1 public class CoreServlet {
     2 
     3     public boolean uploadFile(InputStream is, String path) throws Exception {
     4         String fileName = path.substring(path.lastIndexOf("\") + 1, path.length());
     5         FileOutputStream fos = new FileOutputStream(new File("E://" + fileName));
     6         byte[] b = new byte[1024];
     7         while ((is.read(b)) != -1) {
     8             fos.write(b);
     9         }
    10         is.close();
    11         fos.close();
    12         return true;
    13     }
    14 
    15 }
  • 相关阅读:
    怎样打开64位 Ubuntu 的32位支持功能?
    HDOJ 1312题Red and Black
    课程设计,文件加密
    一首诗的代码
    HDOJ1021题 Fibonacci Again 应用求模公式
    HDOJ 1013题Digital Roots 大数,9余数定理
    codevs 3314 魔法森林
    codevs 1144 守望者的逃离
    Wormholes
    codevs 1507 酒厂选址
  • 原文地址:https://www.cnblogs.com/Oven5217/p/7469510.html
走看看 - 开发者的网上家园