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 }
posted @ 2017-09-03 14:22  我滴个小张张  阅读(530)  评论(0编辑  收藏  举报