六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 56|回复: 0

struts 上传任意多个文件

[复制链接]

升级  6.67%

58

主题

58

主题

58

主题

举人

Rank: 3Rank: 3

积分
220
 楼主| 发表于 2013-2-7 16:07:21 | 显示全部楼层 |阅读模式
转自:http://1zebra.iteye.com/blog/427260
 
<div class="blog_content">在struts1.x中,若使用FormFile[]数组来做批量上传并不能成功。

下面这种方法只是通过struts1.x中的MultipartRequestHandler来获取<input type="file" />控件来达到批量上传的目的

1.jsp页面为
<html:file property="files(0)" />
        <html:errors property="files" />
        <div id="uploadFile"></div>
        <a href=""> <input type="button" value="上传更多"
           />
        <script>
         i=1;
         function addItem(){
          document.getElementById('uploadFile').innerHTML+='<input type=\"file\" name=\"files('+i+')\"><br/> ';
          i++;
         }
        </script>

2 form表单
//目的是不让struts报错
private List<FormFile> files = new ArrayList<FormFile>();

public List<FormFile> getFiles() {
   return this.files;
}

3.action为
//获取formfile
   ContentPublishForm contentPublishForm = (ContentPublishForm) form;
   MultipartRequestHandler multipartRequestHandler = form
     .getMultipartRequestHandler();
   // 取得所有上传文件的对象集合
   Hashtable elements = multipartRequestHandler.getFileElements();
   // 循环遍历每一个文件
   Collection values = elements.values();
   int k = 0;
   for (java.util.Iterator i = values.iterator(); i.hasNext();) {
    FormFile file = (org.apache.struts.upload.FormFile) i.next();// 取得上传的文件
    if ("" != file.toString()) {
     FileOutputStream fileOutput;
     try {
      String fileUrl = request
        .getRealPath("//Image//"
          + file.getFileName());
      fileOutput = new FileOutputStream(fileUrl);
      fileOutput.write(file.getFileData());
      fileOutput.flush();
      fileOutput.close();
     } catch (FileNotFoundException e) {
      e.printStackTrace();
     } catch (IOException e) {
      e.printStackTrace();
     }
    }
   }
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表