struts2 多文件上传

多文件上传,还整个列表操作,坑爹!

效果图:



 前台页面JSP:

from 要加 enctype="multipart/form-data"
  <div id="upFile">
   上传发票附件(需提交上传后才可进行下载):<input type="file" name="image" id="j" οnchange="addfile('j')">
  </div>

  <div
   style="height:125px;overflow-y:scroll;width: 800px;">
   <table id="uploadTable" cellspacing="0">
    <tr>
     <th width="600px">名称</th>
     <th width="200px">操作</th>
    </tr>
   </table>
  </div>

 

js:

//上传文件隐藏并增加队列

var i=0;

var uploadArray = new Array();//记录删除的文件名称
 function addfile(id){
  $("#"+id).hide();
  newid="j"+i+"";
  $("#upFile").append("<input type='file' name='image' id='"+newid+"' οnchange='addfile(&quot;"+newid+"&quot;)'>");
  var arr= $("#"+id).val().split('\\');
  var fileName=arr[arr.length-1];
  var newRow = "<tr id='"+id+"' ><td id='fileNameTd' >"+fileName+"</td><td id='operTd'><input type='button' οnclick='del(&quot;"+id+"&quot;)' value='删除'></td></tr>";
  $("#uploadTable tr:last").after(newRow);
  i++;
 }
 
 //删除待上传的文件
 function del(id){
  var arr= $("#"+id).children("td[id='fileNameTd']").text();
  uploadArray.push(arr);
  $("#uploadTable tr[id='"+id+"']").remove();
  $("#"+id).remove();
 }

 

后台:

需绑定

 private File[] image; // 上传的文件
 private String[] imageFileName; // 文件名称
 private String[] imageContentType; // 文件类型

 

/**
  * 多文件上传并返回需要保存的list
  *
  * 这里的fireName是保存的文件夹名称,保存的文件名称加了时间戳的避免重复
  */
 public ArrayList<Uploadfile> upload(String fireName) {
  ArrayList<Uploadfile> uploadfileList = new ArrayList<Uploadfile>();
  try {
   ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
   String realpath = ServletActionContext.getServletContext()
     .getRealPath("/upload/"+fireName);
   
   File outfile= new File(realpath);     
     if(!outfile.isFile()){
         outfile.mkdir();
   }
   if (image != null) {
    File savedir = new File(realpath);
    if (!savedir.getParentFile().exists())
     savedir.getParentFile().mkdirs();
    for (int i = 0; i < image.length; i++) {
     String upFileName = System.currentTimeMillis()+ imageFileName[i];
     File savefile = new File(savedir,upFileName);
     FileUtils.copyFile(image[i], savefile);
     Uploadfile up = new Uploadfile();
     up.setFileName(imageFileName[i]);// 文件名称
     up.setAddress("/upload/" + fireName + "/" + upFileName);// 文件地址
     uploadfileList.add(up);
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return uploadfileList;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值