Fork me on GitHub

新博客地址:voidy's blog

Struts之上传

Posted on 2014-08-25 09:45  尛鱼  阅读(158)  评论(0编辑  收藏  举报

上传的jsp写法:

   <tr>
        <td width="50%" align="left">软件上传:
        <input  type="file" size="20" class="form-control" name="file" required></td>
   </tr>

上传的table的表格的form表单需要有的属性(橘黄色标记):

1 <form action="software_add" method="post" class="form" id="form"  enctype="multipart/form-data">
2 ...
3 </form>

上传的后台java相关代码:

 1 try {       
 2              is = new FileInputStream(file);   
 3              switch (software.getType()) {
 4                 case 1:
 5                      os = new FileOutputStream(new File("D:\upload\program\", fileFileName));    
 6                     break;
 7                 case 2:
 8                      os = new FileOutputStream(new File("D:\\upload\\net\\", fileFileName));    //转义不转义均可
 9                     break;
10                 case 3:
11                      os = new FileOutputStream(new File("D:\\upload\\app\\", fileFileName));    
12                     break;
13                 default:
14                     break;
15                 }   
16             System.out.println("fileFileName: " + fileFileName);
17             // 因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的fileFileName是否相同
18             System.out.println("file: " + file.getName());
19             System.out.println("file: " + file.getPath());   
20             path = file.getPath();
21             byte[] buffer = new byte[500];
22             int length = 0;
23             
24             while(-1 != (length = is.read(buffer, 0, buffer.length)))
25             {
26                 os.write(buffer);
27             }
28             
29            
30             
31         } catch (Exception e) {
32             // TODO: handle exception
33              System.out.println("文件上传失败");
34               e.printStackTrace();
35         }
36         
37         finally {
38              
39               try {
40                 is.close();
41                 os.close();
42             } catch (IOException e) {
43                 // TODO Auto-generated catch block
44                 e.printStackTrace();
45             }
46         }

Struts部分还可以通过以下控制上传文件大小:

<struts>
<
constant name="struts.multipart.maxSize" value="10701096"/>
...
</struts>

PS;此属性需放到<struts></struts>之间