ajaxuploadiy 多文件上传

8 篇文章 0 订阅
1 篇文章 0 订阅
这篇博客详细介绍了如何在JSP页面中利用ajaxFileUpload实现多文件上传功能。通过创建动态输入框,用户可以选择多个文件进行上传。在js代码中,利用jQuery的ajaxFileUpload插件,将文件发送到后端Java控制器。控制器接收到文件后,将其保存到服务器,并返回文件路径。同时,前端页面会展示上传成功的图片,并提供删除图片的功能。
摘要由CSDN通过智能技术生成

jsp页面:

<table>

<tr>
         <td>上传图片:</td>
         <td>
                       <input type="button"  value="添加图片" οnclick="createInput('fileQueue');" /> 
                       <input type="button" name="tijiao" value="上传" οnclick="upload()">
                       <div id="fileQueue"></div>
                       <br/><div id="imageDiv"></div> 
                       <input type="hidden" value="${deptInfo.images}" name="images" id="images"/>
         </td>
       </tr></table>

js代码:

<script type="text/javascript">
      $(document).ready(function(){
            });
   
   function upload(){
        var uplist = $("input[name^=uploads]"); 
        for (var i=0; i< uplist.length; i++){ 
         if(uplist[i].value){ 
             $.ajaxFileUpload(
                {
                    url: '${pageContext.request.contextPath}/dept/upload', //用于文件上传的服务器端请求地址
                    secureuri: false, //是否需要安全协议,一般设置为false
                    fileElementId: uplist[i].id, //文件上传域的ID
                    dataType: 'json', //返回值类型 一般设置为json
                    success: function (data)  //服务器成功响应处理函数
                    {
                        if (typeof (data.result) != 'undefined') {
                            if(data.result == ('success')){
                                var vv = (data.imgurl).split('|');
                    var imageUrl = vv[0].split("/")[2];
                    var html="<img οnclick='showdiv(\""+imageUrl+"\")' name='"+imageUrl+"' id='"+imageUrl+"' style='width:100px;height:100px;' src='${pageContext.request.contextPath}/"+vv[0]+"'/>";
                       html += "<a class='"+imageUrl+"' href='javascript:void();' οnclick=\"deleteImage(this,'"+imageUrl+"')\">删除</a>";
                    $("#imageDiv").append(html);
                    var images;
                    if($("#images").val().length != 0){
                      var images =  $("#images").val()+";"+imageUrl;
                    }else{
                       images = imageUrl;
                    }
                    $("#images").val(images);
                            }else{
                              alert("上传失败!");
                            }
                        }
                       $("#fileQueue").empty();
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        alert(e);
                    }
                }
               )
         } 
        }
    }
   
   //删除图片
   function deleteImage(deleteA,imageUrl){
      $.ajax({
           type:"post",
   url:"${pageContext.request.contextPath}/dept/deptImage",
   async:false,
   cache:false,
   data:"imageUrl="+imageUrl,
   success:function(msg){
    if(msg!=''){
        alert(msg);
        $(deleteA).remove();
          var thisNode=document.getElementsByName(imageUrl);
        for(var i=0;i<thisNode.length;i++){
           document.getElementById("fileQueue").removeChild(thisNode[i]);
        }
        //修改images的值
        var image = "";
        $.each($("#imageDiv").find("img"),function(i,img){
              image += $(img).attr("name")+";";
           });
           $("#images").val(image.substring(0,image.length-1));
    }
   },
   error:function(){
    $.messager.alert('警告','系统异常!','error');
   }
       });
   }
   
    var count = 1;
   /**
 * 生成多附件上传框
 */ 
 function createInput(parentId){ 
     count++; 
     var str = '<div name="div" >'+ 
     '   '+ '<br/><input type="file" contentEditable="false" id="uploads' + count + '' + 
     '" name="uploads'+ count +'" value="" style="width: 220px"/><input type="button"  value="删除" οnclick="removeInput(event)" />'+'</div>'; 
     $("#fileQueue").append(str); 
 } 
 /**
 * 删除多附件删除框
 */ 
 function removeInput(evt, parentId){ 
    var parentId = 'fileQueue';
    var el = evt.target == null ? evt.srcElement : evt.target; 
    var div = el.parentNode;
    var cont = document.getElementById(parentId);        
    if(cont.removeChild(div) == null){ 
     return false; 
    } 
    return true; 
 }  
   
</script>

java后台控制器:

/**
  *
  * @Title: uploadImage
  * @Description: 上传网点图片
  * @param request
  * @param response
  * @throws IOException
  * @return void
  * @author zgj
  * @date 2016年3月21日 下午2:53:06
  */
 @RequestMapping(value="/upload")
 public void uploadImage(HttpServletRequest request,HttpServletResponse response) throws IOException{
  
        String responseStr = "";
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取前台传值
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String configPath = "upload/images/";
        String ctxPath = request.getSession().getServletContext().getRealPath("/");
  
        ctxPath += configPath;
        // 创建文件夹
        File file = new File(ctxPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = null;
        String res = "";
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 上传文件名
            MultipartFile mf = entity.getValue();
            fileName = mf.getOriginalFilename();

            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
            responseStr = configPath + newFileName + "|" + fileName;
            res = "{result:'success',imgurl:'" + responseStr + "'}";

           
            File uploadFile = new File(ctxPath + newFileName);
            try {
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
            } catch (IOException e) {
                responseStr = "fail";
                res = "{result:'" + responseStr + "'}";
                e.printStackTrace();
            }
        }
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        // 这句话的意思,是告诉servlet用UTF-8转码,而不是用默认的ISO8859
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(res);
 }

 ps:js文件见资源下载~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值